Yingfa
Yingfa

Reputation: 55

Project Euler Solution 9 Code Not Working

function getAnswer(){
    var answer, c = 334;
    while (c < 999){
        var a = Math.round(((1000 - c) / 2) - 0.5), b = Math.round((1000 - c) / 2);
        while (a > 0 && b < c){
            if (Math.pow(a, 2) + Math.pow(b, 2) != Math.pow(c, 2)){
                a -= 1;
                b += 1;
            }else{
                answer = a * b * c;
            }
        }
        c += 1;
    }
    document.getElementById("a").innerHTML = answer;
}

Hi! I am a beginner programmer in javascript, and I have been trying to solve problem 9 in Project Euler. That problem goes like this:

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.

There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.

I don't know why no answer appears, and my script crashes/program stops running, whenever I run this script. Please explain and tell me what's wrong with my script.

Upvotes: 0

Views: 106

Answers (1)

Bergi
Bergi

Reputation: 664886

When you have found the answer, you don't stop with the iteration. Even worse, you don't change the values of a and b any more, so they never reach the end of the iteration, and you're stuck in an infinite loop.

You'll need to break out of the loop when you've found the answer. Or even break out of both your nested loops, using a label:

function getAnswer() {
    var answer,
        c = 334;
    find: while (c < 999) {
        var a = Math.round(((1000 - c) / 2) - 0.5),
            b = Math.round((1000 - c) / 2);
        while (a > 0 && b < c) {
            if (Math.pow(a, 2) + Math.pow(b, 2) == Math.pow(c, 2)) {
                answer = a * b * c;
                break find;
            }
            a -= 1;
            b += 1;
        }
        c += 1;
    }
    document.getElementById("a").innerHTML = answer;
}

Notice that it would be easier if your function just returned the answer, instead of populating #a with it. You'd call it like

document.getElementById("a").innerHTML = getAnswer();

and can just return a * b * c; to break out of the whole function.

Upvotes: 3

Related Questions