Frage

I'm trying to solve Problem 10 in Project Euler, and while I thought I had it, its saying my answer is incorrect. The question is as follows:

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million.

And my code:

int sum;
@interface Prime : NSObject
-(BOOL)isPrime:(int)arg1;
@end

@implementation Prime
-(BOOL)isPrime:(int)arg1 {
    if (arg1 == 1) {
        NSLog(@"Given 1");
        return NO;
    }
    for (int i = 2; i < arg1; i++) {
        if (arg1 % i == 0) {
            return NO;
        }
    }
    sum += arg1;
    return YES;
}
@end

int main(int argc, const char * argv[])
{

    @autoreleasepool {
        Prime* primeObject = [[Prime alloc] init];
        for (int i = 0; i < 2000000; i++) {
            [primeObject isPrime:i];
        }
        NSLog(@"Sum of primes is %i", sum);
    }

}

This code outputs 'Sum of primes is 1179908154' which Project Euler says is incorrect. Help?

War es hilfreich?

Lösung

The problem is that the sum does not fit into a 32-bit integer. You should use long long instead.

Andere Tipps

Just a guess, you should try to:

  • Initialise the sum variable to 0.
  • Try not to use a global variable like sum that can be accessed from anywhere, in this case do the sum in the main loop instead of in the isPrime method.

Maybe that'll give you the right answer.

You are using int for getting result, so it is wrong. I'm using long int instead, that is enough for this case.

Here is my code, and it works fine:

    int inputNumber = 2000000;
    long int result = 0;

    for (int i = 2; i < inputNumber; i++) {
        BOOL isPrime = YES;
        for (int j = 2; j <= sqrt(i); j++) {
            if (i%j==0) {
                isPrime = NO;
                break;
            }
        }

        if (isPrime) {
            result += i;
        }
    }

Result is: 142913828922

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top