How to Solve a Problem 4: Where is the number?
Ran into this problem on reddit, and figure I'd give this a try on how to solve it.
I need to find which line a certain number is, like:
First Line - 1
Second Line - 2 3 4
Third Line - 5 6 7 8 9
Fourth Line -> 10 11 12 13 14 15 16
Fifth Line -> 17 18 19 20 21 22 23 24 25
Nth line - (...) 1969 (...)
What is N?
Always study the data given, and find the pattern. We need to solve this with a program.
In this case, the pattern is pretty obvious: the line ends in the square of the number. 5th line ends in 25 (5^2).
So to get N, we take the square root of 1969, and it turns out to be 44.something.
44*44 = 1936.
So it's obvious that 1969 is on the NEXT line, N=45.
But how do you do this programmatically? The original question called for Python, but we'll do this in JavaScript, as it's quite simple.
We need to keep testing N and increment N until N^2 is larger than 1969.
let bFound=false
let n=1
while (!bFound) {
if ((n^2)>=1969) {
bFound=true }
else {
n++ }
}
//n is now the answer
Bonus: I calculated the answer WITHOUT a loop. Can you find the formula?
Comments
Post a Comment