Project Euler Problems for Learn Programming - Solution 5 (Python & Javascript)

in #javascript7 years ago (edited)

Project Euler
Hey SteemIt community. Did you heard about Project Euler? If you don't know please review this website: Project Euler

Problem 5

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

Solution (Python)

check = range(10,21)
a = 21
b = False

while b == False:
    if a % 2520 == 0:
        if all(a % n ==0 for n in check):
            b = True
        else:
            a = a + 2520
    else:
        a = a + 1
print(a)

Solution (Javascript)

var from = 1,
    target = 20,
    primes = {},
    result = 1;

for (var divider = from; divider <= target; divider++) {
    (function (newTarget) {
        var i = 2,
            dividersPrimes = {};
        while (i <= newTarget) {
            while (newTarget % i === 0) {
                newTarget = newTarget / i;
                if (!dividersPrimes[i]) {
                    dividersPrimes[i] = 1;
                } else {
                    dividersPrimes[i]++;
                }
            }
            i++;
        }
        for (var prime in dividersPrimes) {
            if (dividersPrimes.hasOwnProperty(prime) &&
                (!primes[prime] ||
                    primes[prime] < dividersPrimes[prime])) {
                primes[prime] = dividersPrimes[prime];
            }
        }
    })(divider)
}
for (var prime in primes) {
    if (primes.hasOwnProperty(prime)) {
        result = result * Math.pow(prime, primes[prime])
    }
}
console.log(result);

Result = 232792560

Javascript Solution Source

Sort:  

This post recieved an upvote from minnowpond. If you would like to recieve upvotes from minnowpond on all your posts, simply FOLLOW @minnowpond