-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
74 lines (50 loc) · 1.42 KB
/
index.js
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
// Global Valiables
let cycles = 0;
let primes = [];
// FUNCTION: isPrime
// Description: Check if one number is prime
// Arg: int number
// Return: boolean
export default function isPrime(numberForTest = 7919){
if( numberForTest < 1 ) return [ 'error', [] ];
let result = true;
primes = [2];
if( numberForTest == 1 ) {
primes = [];
result = false;
}
console.time('Time');
for(let x=3; x <= numberForTest; x=x+2){
result = checkPrime(x);
}
console.timeEnd('Time');
// INFOS:
console.log( 'Is prime:', numberForTest, result );
console.log( 'Quantity:', primes.length, 'primes' );
console.log( 'All primes found:', primes );
console.log( 'Necessary "for()" cycles:', cycles );
return [ result, primes ];
} // isPrime
// FUNCTION: checkPrime
// Description: Check if one number is prime
// Arg: int number
// Return: boolean
const checkPrime = function(number){
const sqrtNumber = Math.sqrt(number);
let checkPrime = true;
let primesLength = primes.length;
for(let i=0; i <= primesLength; ++i){
++cycles; // used only for DEV, comment = +20% faster
const currentValue = primes[i];
if(currentValue > sqrtNumber) {
checkPrime = true;
break;
}
if(number % currentValue === 0) {
checkPrime = false;
break;
}
}
if(checkPrime) primes.push(number);
return checkPrime;
} // checkPrime --------------------------------------------