开发者

F# fails with "Error 4 This expression was expected to have type int but here has type int -> int"

Here is the code that I am trying to get to work last line is where it is failing:

let rec gcd a b =
    if b= 0 then
        a
    else
        gcd b (a % b);;

let n = 8051
let mutable d = 0
let mutable c = 1
let mutable xi = 2
let mutable yi = 2
let f x = (pown x 2) + (c % n);;
while c < 100 do
    while d = 1 do
        xi <- (f xi)
        yi <- (f(f(yi)))
        printfn "%d%d" xi yi        
        d <- gcd(abs (xi - yi) n)

---------------------The Following Code works; Except for integer overflow on N---------

module Factorization


let rec gcd a b =
    if b= 0 then
        a
    else
        gcd b (a % b);;

let n = 600851475143N
let mutable d, c, xi, yi = 1, 1, 2, 2
let f x = (pown x 2) + (c % n);;

let maxN m =int(ceil(sqrt(float m)))
//if (n > maxN(xi)) && (n >  maxN(yi)) then
while c < 100 do
    d <- 1
    while d = 1 do        
        if (maxN(n) > xi) && (maxN(n) >  yi) t开发者_C百科hen
            xi <- f xi
            yi <- f(f(yi))           
            d <- gcd (abs (xi - yi)) n
            //fail
            if d = n then d<-1
            if d <> 1 then printfn "A prime factor of %d x = %d,  y = %d, d = %d" n xi yi d
        else
            xi <- 2
            yi <- 2
            c  <- c + 1;;


In addition to what @Rangoric pointed out, the outer brackets have to go as well otherwise currying won't work:

d <- gcd (abs(xi-yi)) n


Yikes, here are a few unsolicited tips (@BrokenGlass answered the question itself correctly).

First, you can assign all those mutables in one line:

let mutable d, c, xi, yi = 0, 1, 2, 2

Second, go easy on the parentheses:

xi <- f xi
yi <- f (f yi)

And of course, try to get rid of the mutables and while loops. But I'll leave that to you since I'm sure you are aware seeing that you implemented gcd using recursion.


Try:

d <- gcd (abs(xi-yi)) n

It is pointing out that abs is a int->int and not an int by itself. Wrapping it in parentheses causes the abs to be executed before gcd looks at it. This causes gcd to see the result of abs instead of abs itself.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜