Skip to the content.

Project Euler Problem 26

リンク

解法(Haskell)

main関数

main::IO()
main = problem26

素数を判定する関数

isPrime::Integer -> Bool
--素数を判定する
isPrime 1 = False
isPrime x = [n| n <- [1.. floor $ sqrt $ fromIntegral x], mod x n == 0] == [1]

要素を絞る関数

findLongLoop::Integer->[Integer]->Integer
--nを増やしながら要素が1つになるまで10^n -1 を割り切るものを除外する
findLongLoop n xs
    | n >= 1000 = -1 --1000を超えたら失敗
    | length xs == 1 = xs!!0
    | otherwise = findLongLoop (n+1) [y|y<-xs, mod (10 ^ n - 1) y /= 0]

解く

problem26::IO()
problem26 = do
    let list = takeWhile (<1000) $ [x|x<-[7..], isPrime x]--2と5は循環小数を作らないので除外
    print $ findLongLoop 1 list

戻る