Hi. We were asked to make a program which displays the prime numbers within the range you inputted... like for example i entered 20 as the upper limit and 1 as the lower, then the program must display all prime numbers within 20 and 1..
and so my problem is, i get to display the prime numbers, but 2, 3, 5, and 7 can't because it think it's with the if statement i made within the loop? any help regarding this?? thanks. (code below)
Do you want to show 2,3,5 and 7 or not. Your question doesn't make any sense to me. If you don't want to show 2 to 7 ,then code given below works well:
Otherwise, the reason it isn't outputting 2, 3,5 or 7 is because when i is 2, 3, 5 or 7 then i%2, i%3, i%5 or i%7 is equal to 0, so it skips that value of i
yep.. that's my problem.. i used i%2, i%3, i%5 and i%7 seven that's why 2, 3,, 5 and 7 cannot be displayed.. i'm also out of ideas on how to do this...
#include <cstdio>
#include <iostream>
bool isPrime( int i ) {
for( int j = 2; j < i; j++ ) {
if( i % j == 0 ) // i is divisible by j, so i is not a prime
returnfalse;
}
// No integer less than i, divides i, so, i is a prime
returntrue;
}
int main() {
int up,low;
scanf("%d ",&up);
scanf("%d",&low);
for( int i = low; i <= up; i++ ) {
if(i<=1)
{
continue;
}
if( isPrime(i) == true )
printf("%d ", i);
}
return 0;
}
for more about generating prime , see this document.