Created
April 18, 2022 15:01
-
-
Save jps/080f23ef19be482cbb05435ee9cc7123 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const assert = require("assert"); | |
| const nextPrime = (primes: Array<number>) : number => { | |
| if(primes.length == 0) | |
| { | |
| return 2; | |
| }else if(primes.length == 1) | |
| { | |
| return 3; | |
| } | |
| let i = primes[primes.length-1] + 2; | |
| while(!primes.every(p => i % p !== 0)) | |
| { | |
| i = i + 2; | |
| } | |
| return i; | |
| } | |
| assert.equal(nextPrime([2]), 3); | |
| assert.equal(nextPrime([2,3]), 5); | |
| assert.equal(nextPrime([2,3,5]), 7); | |
| const isPrime = (n: number) : boolean => { | |
| if(n < 2) | |
| { | |
| return false; | |
| } | |
| let halfN = Math.round(n / 2) +1; | |
| let i = 2; | |
| let primes = []; | |
| while(i< halfN) | |
| { | |
| if(n % i === 0) | |
| { | |
| return false; | |
| } | |
| primes.push(i); | |
| i = nextPrime(primes); | |
| //nextPrime( currentPrimes) | |
| } | |
| return true; | |
| } | |
| const scenarios : Array<[number, boolean]> = [ | |
| [0, false], | |
| [1, false], | |
| [2, true], | |
| [3, true], | |
| [4, false], | |
| [13, true], | |
| [294979, true], | |
| [5445067, true], //timeout | |
| [95328227, true], | |
| [2756621611, true], | |
| ] | |
| scenarios.forEach(([n, expected]) =>{ | |
| console.log(`isPrime:${n} expected:${expected}`); | |
| assert.equal(isPrime(n), expected); | |
| }); | |
| console.log('done'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment