Trying to calculate the sum of all primes < 2M, fault in algorithm

This is a discussion on Trying to calculate the sum of all primes < 2M, fault in algorithm within the C Programming forums, part of the General Programming Boards category; Can anybody see why the following piece of code does not provide the correct output for the calculation of the ...

  1. #1
    Registered User
    Join Date
    Mar 2010
    Posts
    44

    Trying to calculate the sum of all primes < 2M, fault in algorithm

    Can anybody see why the following piece of code does not provide the correct output for the calculation of the sum of all primes < 2 000 000?

    Code:
    #include <stdio.h>
    #include <math.h>
    int isPrime(int numb)
    {
    	int i, stop = 0;
    	for (i = 2; !stop && i <= sqrt(numb); i++) {
    		if (numb % i == 0)
    			stop = 1;
    	}
    	if (!stop)
    		return 1;
    	else
    		return 0;
    }
    
    int main()
    {
    	int i, sum = 2;
    	for (i = 3; i < 2000000; i += 2) {
    		if (isPrime(i)) {
    			printf("%i\n",i);
    			sum += i;
    		}
    	}
    	printf("%i\n", sum);
    	return 0;
    }

  2. #2
    msh
    msh is offline
    Novice
    Join Date
    Jul 2009
    Posts
    568
    What's the max value a signed integer type can store?

  3. #3
    Registered User
    Join Date
    May 2010
    Location
    Naypyidaw
    Posts
    1,314
    >What's the max value a signed integer type can store?
    INT_MAX in limits.h

  4. #4
    Registered User
    Join Date
    Mar 2010
    Posts
    44
    oh god thanks hahaha what a stupid mistake

  5. #5
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,655
    A couple of issues:

    1) isPrime doesn't handle 0 or 1 properly.
    2) sqrt(numb) should really only be calculated once.

    Oh, and just for fun...

    Code:
    int sumOfPrimesUpTo(int numb)
    {
    	int sum = (numb * (numb + 1)) / 2;
    	for (int i = 0; i <= numb; ++i)
    		if (!isPrime(i))
    			sum -= i;
    	return sum;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with yacc/compiler design/seg fault
    By trippeer in forum C Programming
    Replies: 1
    Last Post: 04-08-2005, 03:43 AM
  2. Locating A Segmentation Fault
    By Stack Overflow in forum C Programming
    Replies: 12
    Last Post: 12-14-2004, 12:33 PM
  3. Binary Search Trees Part III
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 16
    Last Post: 10-02-2004, 03:00 PM
  4. Request for comments
    By Prelude in forum A Brief History of Cprogramming.com
    Replies: 15
    Last Post: 01-02-2004, 09:33 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21