Project Euler #6: Sum square difference

Sort by

recency

|

277 Discussions

|

  • + 0 comments

    Don't forget to use long's if working in C/C++. The sums can easily exceed 2^31.

  • + 0 comments

    Haskell

    import Control.Applicative
    import Control.Monad
    import System.IO
    
    
    sqSumTo :: Int -> Int
    sqSumTo n = ((n * (n+1)) `div` 2 ) ^ 2
    
    sumSqTo :: Int -> Int
    sumSqTo n = sum [x * x | x <- [1..n]]
    
    main :: IO ()
    main = do
        t_temp <- getLine
        let t = read t_temp :: Int
        forM_ [1..t] $ \a0  -> do
            n_temp <- getLine
            let n = read n_temp :: Int
            print (sqSumTo n - sumSqTo n)
    
  • + 0 comments

    Kotlin 100% - Use long for the last testcase.

    private fun sumOfSquares(input: Long, sum: Long): Long{
        return if(input == 0L) sum else  sumOfSquares(input - 1, sum+(input*input))
    }
    
    private fun sumOfNumbers(input: Long):Long{
        return (input * (input+1))/2
    }
    
  • + 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))