Fundamentals
Write a function sumOfPrimes(n) that takes an integer n and returns the sum of all prime numbers less than or equal to n.
function isPrime(num) {
if (num <= 1) return false;
for (let i = 2; i <= Math.sqrt(num); i++) {
if (num % i === 0) return false;
}
return true;
}
function sumOfPrimes(n) {
let sum = 0;
for (let i = 2; i <= n; i++) {
if (isPrime(i)) {
sum += i;
}
}
return sum;
}
// Since Node 10, we're using Mocha.
// You can use `chai` for assertions.
const chai = require("chai");
const assert = chai.assert;
// Uncomment the following line to disable truncating failure messages for deep equals, do:
// chai.config.truncateThreshold = 0;
// Since Node 12, we no longer include assertions from our deprecated custom test framework by default.
// Uncomment the following to use the old assertions:
// const Test = require("@codewars/test-compat");
describe("sumOfPrimes", function() {
it("should return the sum of primes less than or equal to the given number", function() {
assert.strictEqual(sumOfPrimes(10), 17);
assert.strictEqual(sumOfPrimes(20), 77);
assert.strictEqual(sumOfPrimes(50), 328);
assert.strictEqual(sumOfPrimes(100), 1060);
assert.strictEqual(sumOfPrimes(1000), 76127);
});
it("should return 0 if the given number is less than 2", function() {
assert.strictEqual(sumOfPrimes(1), 0);
assert.strictEqual(sumOfPrimes(0), 0);
assert.strictEqual(sumOfPrimes(-10), 0);
});
it("should handle large numbers efficiently", function() {
assert.strictEqual(sumOfPrimes(1000000), 37550402023);
});
});
/*def hello_world(world): if world == True: return "Hello World baby" elif world == False: return "No World"*/ // helloWorld = (world) => world == true ? 'Hello World baby': 'No World'; const helloWorld= world => world ? `Hello World baby`:`No World`;
- /*def hello_world(world):
- if world == True:
- return "Hello World baby"
- elif world == False:
- return "No World"*/
- // helloWorld = (world) => world == true ? 'Hello World baby': 'No World';
const helloWorld=(world)=>world==true?`Hello World baby`:`No World`;- const helloWorld= world => world ? `Hello World baby`:`No World`;