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

in #javascript9 years ago

Programming

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

Problem 4

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
Find the largest palindrome made from the product of two 3-digit numbers.

Solution (Python)

multiplicands = []
multipliers = []
palindromes = []

for multiplicand in range(999, 99, -1):
    for multiplier in range(999, 99, -1):
        possible_palindrome = multiplicand * multiplier
        possible_palindrome_str = str(possible_palindrome)
        if possible_palindrome_str == possible_palindrome_str[::-1]:
                multiplicands.append(multiplicand)
                multipliers.append(multiplier)
                palindromes.append(possible_palindrome)

largest_palindrome = max(palindromes)
index = palindromes.index(largest_palindrome)

print("Multiplicand is: " + str(multiplicands[index]))
print("Multiplier is: " + str(multipliers[index]))
print("Palindrome is: " + str(max(palindromes)))

Solution (Javascript)

var palindromes = [];

function reverseString(str) {
    for (var i = str.length - 1, o = ''; i >= 0; o += str[i--]) { }
    return o;
}

for(i=999; i>99; i--) {
    for(j=999; j>99; j--) {
        possiblePalindrome = i * j;
        possiblePalindromeStr = possiblePalindrome.toString();
        if (possiblePalindromeStr == reverseString(possiblePalindromeStr)) {
            palindromes.push(possiblePalindrome)
        }
    }
}

largestPalindrome = Math.max.apply(Math, palindromes);
console.log(largestPalindrome);

Result: 906609

Project Euler - Solution 3

Sort:  

This post recieved an upvote from minnowpond. If you would like to recieve upvotes from minnowpond on all your posts, simply FOLLOW @minnowpond Please consider upvoting this comment as this project is supported only by your upvotes!

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.083
BTC 60990.63
ETH 1575.34
USDT 1.00
SBD 0.47