-
Description I received a fork to my version in python by the user Mc Code. The average runtime for different tries is under 500 ms. The half runtime that the previous version in Javascript, too (1000 ms)
Code function isPrime(n) { if (n < 2) return false; else if (n == 2) return true; else if (n % 2 === 0) return false; for (var x = 3; x <= Math.floor(Math.sqrt(n)); x += 2) {if (n % x === 0) return false;} return true; }
Test Cases function isPrimeCheck(n) { if (n < 2) return false; else if (n == 2) return true; else if (n % 2 === 0) return false; for (var x = 3; x <= Math.floor(Math.sqrt(n)); x += 2) {if (n % x === 0) return false;} return true; } describe("Basic Tests", function(){ it("Low values of n", function(){ Test.assertEquals(isPrime(1), false) Test.assertEquals(isPrime(2), true) Test.assertEquals(isPrime(3), true) Test.assertEquals(isPrime(5), true) Test.assertEquals(isPrime(7), true) Test.assertEquals(isPrime(11), true) Test.assertEquals(isPrime(13), true) Test.assertEquals(isPrime(15), false) Test.assertEquals(isPrime(18), false) Test.assertEquals(isPrime(21), false) }); }); function randint(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } describe("Random Tests", function(){ it("Values of n between 1000 and 10e12", function(){ for (var h = 1; h <= 100; h++) { var n = randint(1000, 1000000000001); var result = isPrimeCheck(n), res = isPrime(n); it("Testing for n = " + n.toString(), function(){ Test.assertEquals(res, result); }) } }) })
Output:
-
- All
- {{group.name}} ({{group.count}})
This comment has been reported as {{ abuseKindText }}.
Show
This comment has been hidden. You can view it now .
This comment can not be viewed.
- |
- Reply
- Edit
- View Solution
- Expand 1 Reply Expand {{ comments?.length }} replies
- Collapse
- Remove
- Remove comment & replies
- Report
{{ fetchSolutionsError }}