Project Euler #6: Sum square difference

Sort by

recency

|

274 Discussions

|

  • + 0 comments

    Here's my solution:

    record = {1:1}
    def sumOfFirstNNumbersSquared(n):
        if n in record:
            return record[n]
        else:
            record[n] = sumOfFirstNNumbersSquared(n - 1) + n ** 2
            return record[n]
    
    
    t = int(input().strip())
    for a0 in range(t):
        n = int(input().strip())
        
        a = ( n * (n + 1) / 2 ) ** 2
        b = sumOfFirstNNumbersSquared(n)
        print(int( abs(a - b)) )
    
  • + 0 comments
    t = int(input().strip())
    for a0 in range(t):
        n = int(input().strip())
        
        sumofsquare = (n*(n+1)//2)**2 
        squareofsum = n*(n+1)*(2*n+1) // 6 
        print(abs(sumofsquare-squareofsum))
    
  • + 0 comments

    why my second case isn't executed? for(int a0 = 0; a0 < t; a0++){ int n; cin >> n; int sum=0; int sqsum=0; int sqaure;

        for(int i=1;i<=n;i++){
             sum+=i;
             sqaure =pow(sum,2);
             sqsum+=pow(i,2);
        }
        int diff=sqaure-sqsum;
         cout<<diff<<endl;
    }
    
  • + 0 comments

    why my second case isn't executed? t = int(input().strip())

    for a0 in range(t):

    n = int(input().strip())
    
    summ_bracket = 0
    
    sum_s = 0
    
    for i in range(1,n+1):
    
        summ_bracket+=i
    
        sum_s += i**2
    
    print((summ_bracket)**2-sum_s)
    
  • + 0 comments

    Had to look up some formulas and do some algebra.

    long ans = n * (n + 1) * (3 * n + 2) * ( n - 1) / 12;