### Prime numbers using loop

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)

 ``123456789101112131415161718192021222324252627282930`` ``````#include #include void prime (int up, int low); main() { clrscr(); int Upper, Lower, i; cout<<"Enter the upper limit: "; cin>>Upper; cout<<"Enter the lower limit: "; cin>>Lower; prime(Upper, Lower); getch(); return 0; } void prime(int up, int low) { int i; for(i=low;i
Last edited on
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:

 ``123456789101112131415161718192021222324252627282930`` ``````#include using namespace std; void prime (int up, int low); main() { int Upper, Lower, i; cout<<"Enter the upper limit: "; cin>>Upper; cout<<"Enter the lower limit: "; cin>>Lower; prime(Upper, Lower); return 0; } void prime(int up, int low) { int i; for(i=low;i
i wanted to show the numbers 2, 3, 5, and 7 but it doesn't show up.. that's what my question is all about.
The big problem with this code is that it will output numbers that aren't prime, eg the program will think that 121 is prime but it isn't.
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...
Try this.
 ``12345678910111213141516171819202122232425`` ``````#include #include 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 return false; } // No integer less than i, divides i, so, i is a prime return true; } 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.

http://lightoj.com/article_show.php?article=1001
Topic archived. No new replies allowed.