Skip to content

Commit 2da850a

Browse files
authored
Create 005.js
1 parent 7e0a351 commit 2da850a

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Diff for: 005.js

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
Source: https://projecteuler.net/problem=5
3+
4+
Problem:
5+
"2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
6+
7+
What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?"
8+
9+
10+
My Algorithm:
11+
12+
This is actually doable without code using number theory, but since this is a GitHub repository with JS solutions, here's the JS algorithm:
13+
14+
1. Define a function to check if number is evenly divisble by all numbers from 1 to 20
15+
2. Use a while loop to increment i by the product of all prime numbers from 1 to 20, since the number has to be a multiple of all the prime numbers from 1 to 20 if it is evenly divisible by all numbers from 1 to 20
16+
3. End the loop when it's divisble by all numbers from 1 to 20
17+
*/
18+
19+
function isEvenlyDivisble(x) {
20+
for (let i = 1; i <= 20; i++) {
21+
if (x % i !== 0) { //if the remainder is not 0, it's not evenly divisble, so return false
22+
return false;
23+
}
24+
}
25+
26+
return true; //if the number survived through all 20 divisbility trials in the for-loop, then return true
27+
}
28+
29+
function solution() {
30+
let incrementBy = 2*3*5*7*11*13*17*19; //product of all prime numbers from 1-20
31+
32+
let i = 0;
33+
while ((!isEvenlyDivisble(i)) || (i === 0)) { //while i isn't evenly divisible or if i is 0 (it's initial value)...
34+
i += incrementBy; //add it by the product of all prime numbers from 1-20
35+
}
36+
37+
return i; //when i is evenly divisble, return it, we now have the answer!
38+
}
39+
40+
console.log(solution()); //the answer!

0 commit comments

Comments
 (0)