I should change my cord to make list of prime nuber between 1 to 100 but i do no
ID: 3758598 • Letter: I
Question
I should change my cord to make list of prime nuber between 1 to 100
but i do not know how to solve it
#include <iostream>
using namespace std;
bool isPrime(int);
int main(){
cout << "Welcome to Prime Number Lister" << endl;
cout << "Please enter an integer: ";
int n;
cin >> n;
int p = 1;
int counter = 0;
while(counter < n){
p++;
if(isPrime(p)){
counter++;
}
}
cout << "Prime number " << counter << " is " << p << endl;
return 0;
}
bool isPrime(int p){
bool result = true;
if( p < 2){
result = false;
}
else{
int stop = (int) (sqrt(p) + .5);
for(int d = 2; d <= stop; ++d){
if( p%d == 0){
result = false;
break;
}
}
}
return result;
}
Explanation / Answer
you are complicating your code the logic is simple i.e's prime number factors are 1 and itself
so take two variables one is from list like 5 then j is incremented from 1 to 100 it checks 5%1 and soon if it gets zero for 1 and itself then it is printed as output.
#include<iostream>
int main ()
{
cout<<1;
for (int i=2; i<100; i++)
for (int j=2; j<i; j++)
{
if (i % j == 0)
break;
else if (i == j+1)
std::cout << i << " ";
}
return 0;
}