How Do You Write A Program In C++ To Find The First 'N' Prime Numbers?

4 Answers

Florio Potter Profile
Florio Potter answered

//Finding prime numbers

#include <iostream>

using namespace std;

int main()

{

int n; //User input

int num = 1; //number that will be tested if its a prime

int primeCount = 0; //counts the times it num % i == 0

cout<< "Enter how many prime numbers you want.
";

cin>> n; //Number of prime numbers you want

//prints 1 as a prime number

cout<< 1 << 'n';

//counts the number of primes

for(int j = 1; j <= n; j++)

{

  num++;//num = 2

  primeCount = 0;

//Determines if a number is prime

  for(int i = 1; i
<= num; i++)

  {

  if(num % i ==
0)

  {


primeCount++;

  }

  }

  if(primeCount
== 2)

  {


cout<< num << 'n';

  }

}

return 0;

}

For more information you can get help at  CodeAvail- Online Computer Science Assignment
help

Alongbar Daimary Profile

A Program In C++ To Find The First 'N' Prime Numbers:

#include<iostream.h>
#include<conio.h>

void OutResult(int number){

bool prime=true;
for(int I=2;I<number;I++){
    if(number%I==0){
        prime=false;
        break;
    }
}
if (prime)
cout<<number<<",";
}

void main(){
int number=0;
cout<<"Enter a number to check:";
cin>>number;
for(int I=1;I<=number;I++)
    OutResult(I);

getch();
}
Anonymous Profile
Anonymous answered
Program coding is:-

#include
#include
void main()
{
float x, I, j, a ;
coutx;
For( j = 1;j
Julii Brainard Profile
Julii Brainard answered
I am not going to tell you the code. But here's the basic algorithm. N=number of primes you want.

Set up a counter (M). Initialised to 0.

Set up an array (A) of length N. Initialise all to zero.

Set up a moving test number (T), moving denominator=D=2.

Assume that the first 3 numbers in the array are 1, 2, 3.
IF N=1, the answer is 1, N=2,
IF N=2, answer=(1,2),
If N=3, answer is (1,2,3).
END programme if N<=3.

Else, start with array space M=4, T=4, D=2 .
Maximum D value is trunc[ (T/2)] + 1.

TEST START
POINT A
Test whether mod(T/D)=whole number. If yes
T=T+1; D=2; back to TEST START
else (if no)
D=D+1,
If D< trunc(T/2) + 1,.
goto POINT A
else (D>= trunc(T2) + 1, so prime number must have been found)
Thus If D reaches this value, then
A[M]=T; T=T+1; D=2; M=M+1. Now, If M < N+1 then back to TEST START. Else (M has reached maximum, so time to end, break out of loop)

end, printout all of A[1...N]

Answer Question

Anonymous