I try to print the prime numbers; 2 to 1 million. But nothing printed on the console. Could you check my code? And how can I be this code more optimized?
Here's my code:
#include <stdio.h>
#include <math.h>
main()
{
int num, sr, num2;
for (num = 2; num <= 1000000; num++) {
sr = (int) sqrt(num);
for (num2 = 2; sr % num2 != 0; num2++) {
if (sr == num2) {
printf("%d\n", sr);
}
}
}
}
#include <stdio.h>
#include <math.h>
int main(){
int num, sr, num2;
int isPrime = 1; // this is a check parameter; isPrime = 0 if number is not prime.
for(num=2; num<=100; num++){
sr = (int) sqrt(num);
for(num2=2; num2 <= sr; num2++){
//num2 <== sr to stop the innner loop
if(num%num2 == 0){
//printf("=========== %d|%d\n", num,num2); // uncomment this to see if a number is divisable
isPrime = 0; // this number is not prime, cos num can be divided by num2
break;
}
}
if(isPrime){
printf("Prime number is %d\n", num);
isPrime = 1; // reset the check parameter
}else{
isPrime = 1; // reset the check parameter
}
}
return 0;
}
This code works. Since it works, i'll let you play with it and optimize it. If you can't let us know. We'll try to help you.
I like how you used sqrt to optimize the code.
Did it compile?
line 4: main() should be int main()?
another thing: sr = 1. 1 modulo any number is 1.
and finally. sr will never be equal to num2, because sr is 1 and num2 is 2 or greater so it will never print anything.
this will get you into an infinite loop that does nothing
If you wish to optimize it, you should use something like the sieve of eratosthenes.It is easy to operate on your data range. You can read more about it here : http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
One optimization that you can use is the fact that all primes above 3 are of the form 6n+1 or 6n-1 and the fact that if a number is divisible by a prime, it is not a prime. Here is some code that uses that fact:
#include <stdio.h>
#include <math.h>
int is_prime(long num)
{
int k = 1, a = 0, b = 0;
long sr;
switch(num)
{
case 1: return 0;
case 2: return 1;
case 3: return 1;
case 4: return 0;
case 5: return 1;
case 6: return 0;
case 7: return 1;
}
if (num % 2 == 0) return 0;
if (num % 3 == 0) return 0;
sr = (int) sqrt(num);
while (b < sr) {
a = (6 * k) - 1;
b = (6 * k) + 1;
if (num % a == 0)
return 0;
if (num % b == 0)
return 0;
k += 1;
}
return 1;
}
void main(void)
{
int j;
for (j = 0; j<100; j++){
if (is_prime(j))
printf("%d is a prime\n", j);
}
}
This function returns 1 if num is a prime.
来源:https://stackoverflow.com/questions/15464677/prime-numbers-optimization-in-c