Program to print first 10 prime numbers
Last Updated :
10 Feb, 2024
Write a program to print the first 10 prime numbers.
Note: A number N is said to be prime if it has exactly two factors i.e. 1 and the number itself N
Output Format:
2, 3, 5, 7, 9…
Approach:
Prime Test: To check whether a number N is prime we can check its divisibility with each number from 2 to N – 1, If it is divisible by any number in this range, we can conclude that N is not a prime number.
Looping until first 10 primes are not found: We can use a while loop to continue our prime check on the numbers until we print the first 10 prime numbers.
Step-by-step algorithm:
- Maintain a variable cnt = 0 to keep track of number of primes printed so far.
- Maintain a variable num = 2 to keep track of the number to be checked for prime.
- Run a loop till cnt is less than 10.
- If num is prime, increment cnt by 1.
- Increment num by 1.
- After cnt becomes 10, we have printed the first 10 prime numbers.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
bool isPrime( int N)
{
for ( int i = 2; i < N; i++) {
if (N % i == 0)
return false ;
}
return true ;
}
int main()
{
int cnt = 0;
int num = 2;
while (cnt < 10) {
if (isPrime(num)) {
cout << num << endl;
cnt++;
}
num++;
}
}
|
Java
public class PrimeNumbers {
public static boolean isPrime( int N) {
for ( int i = 2 ; i < N; i++) {
if (N % i == 0 ) {
return false ;
}
}
return true ;
}
public static void main(String[] args) {
int cnt = 0 ;
int num = 2 ;
while (cnt < 10 ) {
if (isPrime(num)) {
System.out.println(num);
cnt++;
}
num++;
}
}
}
|
Python3
def is_prime(N):
for i in range ( 2 , N):
if N % i = = 0 :
return False
return True
def main():
cnt = 0
num = 2
while cnt < 10 :
if is_prime(num):
print (num)
cnt + = 1
num + = 1
if __name__ = = "__main__" :
main()
|
C#
using System;
class Program
{
static bool IsPrime( int N)
{
for ( int i = 2; i < N; i++)
{
if (N % i == 0)
return false ;
}
return true ;
}
static void Main()
{
int cnt = 0;
int num = 2;
while (cnt < 10)
{
if (IsPrime(num))
{
Console.WriteLine(num);
cnt++;
}
num++;
}
}
}
|
Javascript
function isPrime(N) {
for (let i = 2; i < N; i++) {
if (N % i === 0)
return false ;
}
return true ;
}
let cnt = 0;
let num = 2;
while (cnt < 10) {
if (isPrime(num)) {
console.log(num);
cnt++;
}
num++;
}
|
Output
2
3
5
7
11
13
17
19
23
29
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...