-
Notifications
You must be signed in to change notification settings - Fork 0
/
Examples With Comments
78 lines (64 loc) · 1.99 KB
/
Examples With Comments
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
//fibonacci as recurisve problem
function fibonacciRecursion(n) {
if (n = 0) {
n = 1;
fibonacciRecursion(n)
} else {
var fibParam1 = n - 1;
var fib2Parm2 = n - 2;
var fib1 = fibonacciRecursion(fibParam1) + fibonacciRecursion(fibParam2);
console.log(fib1);
}
}
//fibonacci as iterative problem
var count = 0;
function fibonacciIteration(a, b, count) {
if (a = 0) {
count++;
return b;
} else {
var fib1 = a + b;
a = count - 1;
count++;
console.log(a, fib1, count);
fibonacciIteration(a, fib1, count);
}
}
//1.2.6: Fermats Little Theorem Example
function square(x) { return x * x; }
function is_even(n) {
return n % 2 === 0;
}
function square(x) { return x * x; }
function expmod(base,exp,m) {//base is our random number, others are our potential prime number
if (exp === 0)
return 1;
else if (is_even(exp))//if the number is even use successive squaring
return square(expmod(base,exp/2,m)) % m;//recursive, random number smaller than n compute remaider of a to power of n modulo n
else return (base * expmod(base,exp - 1,m)) % m;
}
function random(n) {
return Math.floor(Math.random() * n);
}
function fermat_test(n) {
function try_it(a) {//try the random number in expmod
return expmod(a,n,n) === a;
}
return try_it(1 + random(n - 1));//generate a as a random number
}
function fast_is_prime(n,times) {//determines number of checks to run
if (times === 0)
return true;
else if (fermat_test(n))
return fast_is_prime(n, times - 1);
else return false;
}
fast_is_prime(91,3);
//1.3.1 Functions As Arguments
//Creating a function that can take other functions within, functions passed in as parameters to be interchanged
function sum(term,a,next,b) {
if (a > b)
return 0;
else return term(a) +
sum(term,next(a),next,b);
}