Search code examples
smlgreatest-common-divisor

GCD for large numbers


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

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

gives me the following error :

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

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


Solution

  • You treat Int.toLarge as if it's a type, but it's a function. The type you're looking for is IntInf.int. A gcd function would look the same regardless of what type of number you put into it; but you might have to refer to the arithmetic operators from another module.

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

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

    And because SML/NJ's arithmetic operators are overloaded, here's one for IntInf.int:

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