Sum of all the multiples of 3 or 5 below 1000 gives a wrong answer in C

前端 未结 7 1703
失恋的感觉
失恋的感觉 2020-12-22 05:27

Project Euler problem:

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9

7条回答
  •  生来不讨喜
    2020-12-22 06:09

    Your solution with for-loop will be O(n).

    I found a more generic solution O(1).

    Here we can use another multiplies, even non-primes.

    #include 
    
    long gcd(long a, long b) {  
        return b == 0 ? a : gcd(b, a % b);  
    }
    
    long lcm(long a, long b) {  
        return a / gcd(a, b) * b;  
    }  
    
    long sumMultiple(long mult, long to) {
        to = to / mult;
        to *= to + 1;
        return (to >> 1) * mult;
    }
    
    long calc(long a, long b, long n) {
        n--;
        return sumMultiple(a, n) + sumMultiple(b, n) - sumMultiple(lcm(a,b), n);
    }
    
    int main() {
        int n = 1000;
        printf("Sum of multiplies of 3 and 5 is %ld\n", calc(3,5,n));
        return 0;
    }
    

提交回复
热议问题