954,498 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Faster algorithm for prime numbers

This is a program for getting the sum of prime numbers of given range. The problem is that it would take hours if the limit is about 1000000. I've read about the sieve of Eratosten but having difficulties with implementing it. Could someone help to make this piece of code working faster. Best regards.

#include <stdio.h>
#include <math.h>
void prime_num( int num)
{
	double sum = 0;
		bool isPrime=true;
		for ( int i = 2; i <= num; i++)
		{
				for ( int j = 2; j <= num; j++)
				{
						if ( i!=j && i % j == 0 )
						{
						  isPrime=false;
						  break;
						}
				}
				if (isPrime)
				{
				  printf("\nPrime: %d",i);
				  sum = sum + i;
				}
				isPrime=true;
		}
		printf("\nThe sum of primes is: %.0lf\n",sum);

}
int main(){
	printf("Enter a number and I will generate the prime numbers up to that number: ");
int num = 0;
	scanf("%d",&num);
prime_num(num);
	return 0;
}
george61
Junior Poster in Training
59 posts since Jul 2010
Reputation Points: 10
Solved Threads: 6
 

A couple big time savers:

1) You only need to check a number up to (and including) the square root of that number. If the number is prime at that time, then it's prime.

2) increment your loop by 2 for the numbers to be checked for primeness. Even numbers can never be prime if they are higher than 2.

You can read up on the Sieve of Eratosthenes at Wikipedia.

Adak
Nearly a Posting Virtuoso
1,479 posts since Jun 2008
Reputation Points: 425
Solved Threads: 185
 

Also, in your editor's options set the TAB key to add 4 SPACEs instead. All those TABs make the code harder to read.

WaltP
Posting Sage w/ dash of thyme
Moderator
10,506 posts since May 2006
Reputation Points: 3,348
Solved Threads: 944
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: