-
prime numbers re-posted
Hello everyone,
I finally figured out how to write the code I originally thought I was posting
on the weekend.
The purpose of this small program is to identify prime numbers.
It seems to work okay until a number is entered that is divisible by 11
(or an elevenish type number). Example-- 33 is identified as prime,
777 is identified as prime, etc.
Any help or comments on this code will be appreciated.
Here's the code. Thanks everyone.
Code:
#include <stdio.h>
int main(void)
{
int number;
printf("Enter a number:\n");
scanf("%d", &number);
int a;
for(a = 2; a < number; a++)
{
if((number % a) == 0)
{
printf("%d is not prime.\n", number);
break;
}
if((number % a) != 0)
{
printf("%d is prime.\n", number);
break;
}
}
return 0;
}
-
Thanks, however if using (number % a) == 0 should only tell me whether or not the number is divisible
by a whole number in such a way that it will not leave a remainder. If the number is prime the remainder of
(number / a) would not be 0.
Am I missing something obvious?
-
rather, you should look at your loop, specifically at your two if conditions.......your loop only executes once, no matter what number you enter
-
actually it won't work for any odd numbers that are not prime numbers - try 15, 21 and so on.
your program checks if a number is divisible by two if it is it returns number is not prime if it isn't number is prime.
the purpose of the for loop is to check how many factors there are of the number other than itself and 1. you need to let it finish its job and then check if it is a prime or not after it is finished- that is place the ifs after the end of the for block. you will also need something in the for block to count how many factors there are of the number aswell.