n8CodeGuru
n8CodeGuru

Reputation: 413

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) then
            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;;

Upvotes: 1

Views: 870

Answers (3)

Rangoric
Rangoric

Reputation: 2799

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.

Upvotes: 1

BrokenGlass
BrokenGlass

Reputation: 160902

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

Upvotes: 2

Stephen Swensen
Stephen Swensen

Reputation: 22297

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.

Upvotes: 2

Related Questions