Project Euler -- 欧拉题集 F#(Fsharp)及Haskell 版 - No.3, No.4

来源:互联网 发布:怎么破解apk软件 编辑:程序博客网 时间:2024/06/05 06:08

No3.

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?


F#:  -- F#需要explicitly告知是UL (uint64_t)

let biggestPrimeFactor  (x:uint64)   =
     let  rec   bpfAux   (x:uint64)   (y:uint64) =
                            if   x = y   then x
                            elif x % y = 0UL then bpfAux (x / y) y
                            else bpfAux  x (y + 1UL)
    bpfAux  x  2UL

let anwser = biggestPrimeFactor 600851475143UL


Haskell:

biggestPrimeFactor x = bpfAux  x  2
           where  bpfAux a b | a == b                 = a
                                            | a `mod` b == 0 = bpfAux (a `div` b) b
                                            | otherwise          = bpfAux a (b+1)

anwser = biggestPrimeFactor 600851475143

Anwser: 6857

后语: 这题不能暴力破解啊,开始时候简单的用 isPrime, isFactor这样一个个数字去判断,结果一个晚上没算出来。

             现在用的是 functor tree, 即:

        60       /  \      2   30         /  \        2    15            /  \           3    5

线性时间。


No4.

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91× 99.

Find the largest palindrome made from the product of two 3-digit numbers.

F#:
let isPalindrome n =  
     let nStr = string n |> List.ofSeq
     nStr = List.rev nStr

let biggestPalindrome3 =
    let max = ref 0
    let rec bpAux a b c =
            if     a = c   then max
            elif  isPalindrome (a * b) && (a*b > !max) then max := (a*b); bpAux a (b-1) c
            elif  b <= c then bpAux (a-1) (a-1) c
            else bpAux a (b-1) c
    bpAux 999 999 100

Haskell:

isPalindrome x = let xText = show x
                  in reverse xText == xText

biggestPalindrom n = let palin = bpAux ( (read . take n $ cycle "9") :: Integer ) (10 ^ (n-1))
                                         in maximum palin
               where bpAux x y = aux2 x x y
                     aux2 a b c | a == c             = []
                                | isPalindrome (a*b) = (a*b) : aux2 a (b-1) c
                                | b <= c             = aux2 (a-1) (a-1) c
                                | otherwise          = aux2  a    (b-1) c

anwser4 = biggestPalindrom 3

Anwser906609

后语:”biggestPalindrom n“ 的n表示是几位的数字,n=5时,这个计算就很慢了,需换算法。



原创粉丝点击