SPOJ 24. Small factorials (FCTRL2) with F#

Problem Definition

You are asked to calculate factorials of some small positive integers.

Input

An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.

Output

For each integer n given at input, display a line with the value of n!

More details about the problem is available here.

Solution

open System
open System.Numerics
let init() = Array.init 158 (fun x -> if x = 0 then 1 else 0)
let minLength (a:int array) : int =
let rec m' (a:int array) i =
match a.[i-1] with
| 0 -> m' a (i-1)
| _ -> i
in
m' a a.Length
let toString' (a:int array) =
let s = System.Text.StringBuilder()
let mLength = minLength a
for i=(mLength-1) downto 0 do
s.Append(a.[i])|>ignore
s.ToString()
let (^*) multiplier (multiplicand:int array)=
let rec multiplyOPT (a:int array) b i acc length=
let l = Math.Min(length,a.Length)
if i< l then
let r = a.[i] * b + acc
a.[i] <- r%10
multiplyOPT a b (i+1) (r/10) length
else
a
in
multiplyOPT multiplicand multiplier 0 0 (multiplicand |>minLength |> (+) 2)
let factorial n =
let rec fac n r =
match n with
| 0 -> toString' r
| _ -> fac (n-1) (n^*r)
fac n (init())
let intFactorial (i : uint64) =
let rec f (i:uint64) (acc:uint64) =
match i with
| 0UL -> acc
| i -> f (i-1UL) (acc*i)
in
f i 1UL
let computeFactorial (n:int) =
if n > 20 then
factorial n
else
(intFactorial (n |> uint64)).ToString();
let solveSpoj24() =
let rec solveLines currentLine maxLines =
if currentLine < maxLines then
System.Console.ReadLine()
|> int
|> computeFactorial
|> printfn "%s"
solveLines (currentLine+1) maxLines
in
match Console.ReadLine() |> Int32.TryParse with
| (true, i) when i > 0 -> solveLines 0 i
| _ -> ()
solveSpoj24()
view raw FCTRL2.fs hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s