LoginSignup
1
0

More than 5 years have passed since last update.

Project EulerをHaskellで解いていく(Problem6: Sum square difference)

Last updated at Posted at 2019-02-20

TL;DR

Haskellの勉強を兼ねてProject Eulerを解いていきます。
始めたばかりでわからないことが多いのでコメント頂けると嬉しいです。

問題文

The sum of the squares of the first ten natural numbers is,

 1^2+2^2+3^2+...+10^2 = 385

The square of the sum of the first ten natural numbers is,

 (1+2+3...+10)^2 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.


最初の10個の自然数について, その二乗の和は,

 1^2+2^2+3^2+...+10^2 = 385

最初の10個の自然数について, その和の二乗は,

 (1+2+3...+10)^2 = 3025

これらの数の差は 3025 - 385 = 2640 となる.
同様にして, 最初の100個の自然数について二乗の和と和の二乗の差を求めよ.

コード

main::IO()
main = do
  let x1 = sum $ map (^2) [1..100]
  let x2 = sum [1..100] ^ 2
  print $ x2 - x1

別回答

func1::[Int] -> Int
func1 = sum . map (^2)

func2::[Int] -> Int
func2 = (^2) . sum

func3::[Int] -> Int
func3 = foldr (-) 0 . (\x -> map (\f -> f x) [func2, func1])

main::IO()
main = do
  print $ func3 [1..100]
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0