WKC
WKC

Reputation: 11

Why does this function return only zero and one? Project Euler JavaScript

This function is for project Euler #45. What I'm trying to find is why a funciton, that will work if I use an integer, won't work if I use a variable to represent that integer. In order words, the value (i), for this function only returns 0 and 1.

function tri(n) {
    return (n*(n+1))/2;

}

function pent(n) {
return (n*(3*n-1))/2;
}

function hex(n) {
    return (n*(2*n-1));
}


for (i=0;i<10000;i++) {
    if (tri(i) === pent(i) && pent(i) === hex(i)) {
        console.log(tri(i));
    }
}

Upvotes: 0

Views: 177

Answers (1)

Pointy
Pointy

Reputation: 413818

You're only getting 0 and 1 logged because those are the only numbers for which the result of each of those three functions is the same (0 or 1). For all other numbers, the three functions return different values.

For that Project Euler problem, you're not supposed to find the values of i for which the values of each function are the same. You're supposed to find values that appear in all three sequences. They don't have to appear at the same point in each sequence.

One way to approach the problem is to imagine moving up the lists of T, P, and H numbers from the very start. The first value in each list is 1. Now since they're the same, generate another number for each list. Now the values are 3, 5, and 6. From here on, you can generate a new value for the list whose current value is the smallest of all three. (If there's a tie, pick a list arbitrarily.) That way you keep moving up each list one new value at a time. There may be times when you'll generate two T values without generating another P or H value, but that's OK. Eventually, you'll get to situations where the biggest value on each list is the same, even though the lists aren't the same length.

The challenging and mind-expanding aspect of Project Euler is to think of approaches to the problem yourself. I'll also let on that many of the problems are classic number theory problems, some with surprising solutions. You shouldn't feel bad about not figuring those out if you haven't studied number theory; people who got the solutions first were guys like Euler and Gauss.

Upvotes: 2

Related Questions