• API
• FAQ
• Tools
• Archive
SHARE
TWEET # Untitled a guest Mar 21st, 2019 44 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. package main
2.
3. import (
4.     "fmt"
5.     "time"
6. )
7.
8. const LIM = 41
9. var facts [LIM]uint64
10.
11. func main() {
12.     fmt.Println("==================FACTORIAL==================")
13.     start := time.Now()
14.     for i:=uint64(0); i < LIM; i++ {
15.         fmt.Printf("Factorial for %d is : %d \n", i, Factorial(uint64(i)))
16.     }
17.     end := time.Now()
18.     fmt.Printf("Calculation finished in %s \n", end.Sub(start)) //Calculation finished in 2.0002ms
19.
20.     fmt.Println("==================FACTORIAL CLOSURE==================")
21.     start = time.Now()
22.     fact := FactorialClosure()
23.     for i:=uint64(0); i < LIM; i++ {
24.         fmt.Printf("Factorial closure for %d is : %d \n", uint64(i), fact(uint64(i)))
25.     }
26.     end = time.Now()
27.     fmt.Printf("Calculation finished in %s \n", end.Sub(start)) //Calculation finished in 1ms
28.
29.     fmt.Println("==================FACTORIAL MEMOIZATION==================")
30.     start = time.Now()
31.     var result uint64 = 0
32.     for i:=uint64(0); i < LIM; i++ {
33.         result = FactorialMemoization(uint64(i))
34.         fmt.Printf("The factorial value for %d is %d\n", uint64(i), uint64(result))
35.     }
36.
37.     end = time.Now()
38.     fmt.Printf("Calculation finished in %s\n", end.Sub(start)) // Calculation finished in 0ms
39. }
40.
41. func Factorial(n uint64)(result uint64) {
42.     if (n > 0) {
43.         result = n * Factorial(n-1)
44.         return result
45.     }
46.     return 1
47. }
48.
49. func FactorialClosure() func(n uint64)(uint64) {
50.     var a,b uint64 = 1, 1
51.     return func(n uint64)(uint64) {
52.         if (n > 1) {
53.             a, b = b, uint64(n) * uint64(b)
54.         } else {
55.             return 1
56.         }
57.
58.         return b
59.     }
60. }
61.
62. func FactorialMemoization(n uint64)(res uint64) {
63.     if (facts[n] != 0) {
64.         res = facts[n]
65.         return res
66.     }
67.
68.     if (n > 0) {
69.         res = n * FactorialMemoization(n-1)
70.         return res
71.     }
72.
73.     return 1
74. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.

Top