Project Euler #1: Multiples of 3 and 5

  • + 0 comments
    long long sum_of_multiples(int x, int n) {
        int p = (n - 1) / x; // Largest multiple of x below n
        return (long long)x * p * (p + 1) / 2; // Sum of multiples formula
    }
    int main(){
        int t; 
        scanf("%d",&t);
        for(int a0 = 0; a0 < t; a0++){
            int n; 
            scanf("%d",&n);
            // Sum of multiples of 3 and 5, minus multiples of 15 (to avoid double counting)
            long long sum = sum_of_multiples(3, n) + sum_of_multiples(5, n) - sum_of_multiples(15, n);
    
            printf("%lld\n", sum);
        }
        return 0;
    }