GCD for large numbers

I am trying to create a gcd function that handles very large numbers. Thus, everything I've tried so far leads to errors. For instance:

fun gcd(a : Int.toLarge, b : Int.toLarge): Int.toLarge =
  if   b = 0
  then a
  else gcd(b, a mod b)` 

gives the following error:

Error:unbound type constructor : toLarge in path Int.toLarge

Can someone give me some advice, the rest of my program seems to be working fine. Thank you in advance!

+4
source share
1 answer

You treat Int.toLargeas a type, but it is a function. The type you are looking for is IntInf.int. The gcd function will look the same no matter what type of number you put into it; but you may need to access arithmetic operators from another module.

Here's the gcd function for type Int.int:

fun gcd (a, 0) = a
  | gcd (a, b) = gcd (b, a - b*(a div b))

And since the SML / NJ arithmetic operators are overloaded, here is one for IntInf.int:

fun gcd (a, 0) = a : IntInf.int
  | gcd (a, b) = gcd (b, a - b*(a div b))
+5
source

Source: https://habr.com/ru/post/1696272/


All Articles