The program doesn't print the prime numbers :// "j" indicates prime numbers

#include <iostream>
#include <cmath>
using namespace std;
bool prime(int j);

int main()
{int m;
int n;
int ok;

do
{
cout<< "insert number with which the serie of number will start:" << endl;
cin >> m;
cout << "insert number with which the serie of numbers will end:" << endl;
cin>> n;

cout << "the primes of this serie of number are"<< endl;
for(int j = n; j <= m; j++)
{
if (prime(j)==true)
cout << j;
}


cout << "continue(1) or end(0)?" << endl;
cin>>ok;
}while(ok==1);

return 0;
}

bool prime(int j)
{
if (j < 2) return false;
for(int i=2; i<= sqrt(j); i++) {
if ((j%i) == 0) return false;
}
return true;
}
It works:
insert number with which the serie of number will start:
100
insert number with which the serie of numbers will end:
2
the primes of this serie of number are
2357111317192329313741434753596167717379838997continue(1) or end(0)?
0
The program does work. I also made some touch ups. try it!
Code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <cmath>
using namespace std;
bool prime(int j);

int main()
{int m;
int n;
int ok;

do
{
cout<< "Please insert the number with which the series of number will start(Smaller):" << endl;
cin >> n;
cout << "Please insert the number with which the series of numbers will end(Larger):" << endl;
cin>> m;

cout << "The primes of this series of number are"<< endl;
for(int j = n; j <= m; j++)
{
if (prime(j)==true)
cout << j<<", ";
}
cout << "\ncontinue(1) or end(0)?" << endl;
cin>>ok;
}while(ok==1);

return 0;}

bool prime(int j)
{
if (j < 2) return false;
for(int i=2; i<= sqrt(j); i++) {
if ((j%i) == 0) return false;
}
return true;}
Last edited on
You should invest in looking at the Sieve of Eratosthenes. There are other ways to improve the efficiency of yours though, instead of <= sqrt(j) you can do i*i <=j <= j*j then instead of incrementing by 1 you can increment by 2 and start at 3 instead of 2. You would of course return false if the first bit was set before the loop though. But again, I suggest using a prime sieve.
Last edited on
@giblit: <= j * j? Don't you want to write i * i <= j
Yes that is correct tcs thank you didn't even notice till you said
Topic archived. No new replies allowed.