I need to write to program to list out all prime number from 1 to 100. How to check each number where it is prime or not? give me some advice. Thanks
srk
This is a discussion on How is to check prime number? within the C Programming forums, part of the General Programming Boards category; I need to write to program to list out all prime number from 1 to 100. How to check each ...
I need to write to program to list out all prime number from 1 to 100. How to check each number where it is prime or not? give me some advice. Thanks
srk
/*return 1 if prime */
int isprime(int i)
{
int j;
i=(i>0)?(i) : (-i);
if(i<=1) return 0;
if(i<=3) return 1;
if( (i&1)==0 ) return 0;
for(j=3;j*j<=i;j+=2)
if( (i/j)*j == i) return 0;
return 1;
}
I would use the % operator. It returns the remainder ( 10%3=1 ). A prime number will never return a 0 remainder if divided by a number smaller than itself (except 1).
Maybe create an array and test each value, 1 to 100, recording the result in the aray for the later use (display).
They are searching for a large mersenne prime harnessing the combined power of many small computers , there is even a reward
http://www.mersenne.org/prime.htm
It was the first assignement I received. I have no compiler to test it thought, it might contain mistakes.
ANSI C
Code:#include <stdio.h> int is_prime(int number, int primed) { for (number=1; number < 100; number++) { if ((number%primed)!=0) return 1; } return 0; } int main() { int i; for (i=1; i<100; i++) { if (is_prime(i)==0) printf("%d\n",i); } return 0; }
Thank you!!!
Little problem in the IS-Prime function. Two var in prototype but one in call.
Also all numbers are divisible by 1 so start the loop at two.
Try this;
int is_prime(int number)
{
for (primed=2; primed < number; primed++)
{
if ((number%primed)==0)
return 0;// no remainder so is not prime
}
return 1;//all tested and all have remainder so is prime
}