# 使用javascript函数获取任何给定N的所有素数。

# 方案

  • 首先创建一个函数来检查是否有任何N是素数,用于停止递归,这是必须的。
  • 然后创建一个函数来运行递归。当循环开始时,第一个找到的 i 必须是质数,打破循环并继续向下钻取 j...直到到达结束。

// 首先检查一个数字是否是素数
function isPrime(N) { 
    const result = []; 
    for (let i = 1; i <= N; i++) { 
        if ((N % i === 0)) { 
            result.push(i); 
        } 
    } 
    return !!(result.length === 2); 
} 


//使用递归分解每个因素;
//run 持有递归
//result 持有最终结果
// first check if a Number is prime
function isPrime(N) {

    const result = [];
    for (let i = 1; i <= N; i++) {
        if ((N % i === 0)) {

            result.push(i);

        }

    }

    return !!(result.length === 2);

}


//Using recursion for break down each factor;
//run holds the recursor
//result holds the final result

function getPrime(N) {
    const result = [];
    function run(N) {
        if (isPrime(N)) {
            result.push(N);
            return;
        }
        for (let i = 2; i < N; i++) {
            if ((N % i === 0)) {
                let j = parseInt(N / i);
          //the first i is prime and get pushed   
          run(i);
          //the second one continues to break down
          run(j);
             //need to break the loop for the first factor to prevent duplicates
                break;
            }
        }
    }
    run(N);
    return result;
}
console.log(getPrime(250))



//0,1,1,2,3,5,8…
//write a function that is given a random int of N-the count, and generate a fb sequence
//expect:  fb(0)=0; fb(1)=1, fb(2)=1 fb(3)=2
function fb(N) {

    if (N === 0) {
        return 0;
    } //base case: when to stop

    if (N === 1) {
        return 1;
    } //base case: when to stop

    let sum = fb(N - 1) + fb(N - 2); //variable parameter
    return sum;
}
console.log(fb(6));
//8


function fl(N) {
    const obj = {};
    if (N === 0) {
        return 0;
    }
    if (N === 1) {
        return 1;
    }
    for (let i = 2; i <= N; i++) {
        if (obj[i - 1] !== undefined && obj[i - 2] !== undefined) {
            obj[i] = obj[i - 1] + obj[i - 2];
        } else {
            obj[i] = 1;
            obj[i - 1] = 1;
            obj[i - 2] = 0;
        }

    }

    return obj[N];

}
fl(6);



function fp(N) {
    let n1 = 0,
        n2 = 1,
        nextTerm;
    for (let i = 2; i <= N; i++) {
        nextTerm = n1 + n2;
        n1 = n2;
        n2 = nextTerm;
    }

    return nextTerm;
}
console.log(fp(6))
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123