Next prime number

Hey there,

I'm trying to develop a program to read the next prime number of any number given.

I've got this program i've written up so far but am really stuck as to what's going wrong.. cmd prompt is getting stuck!

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
#include <stdio.h>

int
main(int argc, char **argv) {
   int n, c, x;
 
   printf("Enter a number\n");
   scanf("%d", &n);
 
   
   for ( c = n+1 ;   ; c++ ) {
   	   for (x = 2; x < c; x++) { 
   	   	   if ( c % x == 0 ) {
   	   	   	   if (c == n){
   	   	   	  
   	   	   	   printf("The next prime number is %d", c);
   	   	   	   break;
   	   	   	   }
   	   	   	   } 
       }
   }



        	      


   return 0;
}



Is this the right way of going about this?

Thanks!!
That's called an infinite loop.
1
2
3
4
5
6
7
8
9
10
11
//your code properly indented
	for ( c = n+1 ;   ; c++ ) {
		for (x = 2; x < c; x++) { 
			if ( c % x == 0 ) {
				if (c == n){ //¿when this will be true?
					printf("The next prime number is %d", c);
					break;
				}
			} 
		}
	}
Now read your code.
You start with c=n+1 but your condition is c==n
Then the break will just escape the inner loop, the outter is still an infinite loop
FInally, your "prime" definition is wrong, do it in paper first.
How do I get the code to stop??
It just keeps going..

1
2
3
4
5
6
7
8
9
10
11
12
13
for ( c = n+1 ;  ; c++ ) {
   	   for (x = 2; (x = c); x++) { 
   	   	   if ( c%x == 0) {
   	   	   	   if (c==x){
   	   	   	   printf("The next prime number is %d", c);
   	   	   	   break;
   	   	   	   }
   	   	   }
   	   }
   }

   return 0;
}
Then the break will just escape the inner loop, the outter is still an infinite loop
I'm so confused right nowwwwww.. going round n round in circles :'(
I don't really have a guard though... isn't it just infinite until I find the next prime?!?!
How can I exit the outer loop?
1_ Instead of the inner loop, call a function
1
2
3
for(int candidate = n+1; not is_prime(candidate); ++candidate)
   //This sentence was left blank
   ;


A_ Use a flag
1
2
3
4
5
6
bool is_prime = false;
for(int candidate = n+1; not is_prime; ++candidate){
   //The inner loop that checks primallity
      is_prime = true;
      break; //break the inner loop
}


\alpha_ goto outside;
Topic archived. No new replies allowed.