I've written up some code to find out if a value entered is a prime number. I have now extended this piece of code by adding another function to find the next prime number. I'm having a lot of trouble getting it working, mainly (i think) because I either can't get it to stop once it has found the next one, or, it's just printing the value+1 as the next value (even though it might not necessarily be prime).
My code is as follows:
Code:
#include <stdio.h>#include <stdlib.h>
#include <math.h>
int isperfect(int);
int nextperfect(int);
int
main(int argc, char **argv) {
int value, sum, nextvalue;
printf("Enter two values: ");
while(scanf("%d", &value) == 1){
if(value<0){
printf("Error, negative value!");
exit(EXIT_FAILURE);
}
sum = isperfect(value);
if (sum == value){
printf("The value %d is perfect.\n", value);
}
nextvalue = nextperfect(value);
printf("The next perfect value is %d.\n\n", nextvalue);
}
return 0;
}
int
isperfect(int value){
int divisor, sum = 0;
for(divisor=1; divisor<value; divisor++){
if(value%divisor == 0){
sum = sum+divisor;
printf("The divisor value is = %d, and the value is %d\n", divisor, value);
}
}
return sum;
}
int
nextperfect(int value){
int nextvalue, sum, nextfound;
for(nextvalue = value+1; nextfound == 0 ; nextvalue++){
sum = isperfect(nextvalue);
if (sum == nextvalue){
nextfound = 1;
}
}
return nextvalue;
}