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

  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
    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,708
    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;
    }
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

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, 01: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, 10:33 AM