Tutorial :Prime divisors of a number in ML



Question:

In ML i want to get the prime divisors of a number. How can I do this, I am beginner.


Solution:1

Using the simple trial division, this starts with p=2 and repeatedly divides n by p, incrementing p as it goes.

open LargeInt  (* if you want to work with huge numbers like 5000000000 *)  infix 7 quot rem  val prime_factors =    let fun trial_division p n =      if p > n then nil else        if n rem p = 0          then p :: trial_division  p      (n quot p)          else      trial_division (p + 1)  n    in trial_division 2 end  


Solution:2

There are several general algorithms for finding the prime divisors of an integer: see wikipedia. Trial division with a simple primality test is simplest to understand.

Find or devise an algorithm in pseudocode; only then worry about how to put it into ML.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »