[Javascript] Project Euler #2 (and print answer) in as few characters as possible
1 04 May 2019 03:22 by u/Satirical
Project Euler is a series of programming challenges (https://projecteuler.net) This is problem #2 in the series.
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
Its in one line, but not technically a one liner I don't think, considering there are semicolons.
for(s=0,i=0,j=1,c=0;c!==false;i=j,j=x,c++){x=i+j;if(x<4000000){if(x%2===0){s+=x}}else{console.log(s);break;}}
9 comments
0 u/ThisIsMyRealName 04 May 2019 03:34
That's disgusting and unreadable. Good job.
0 u/boredTech 04 May 2019 05:10
Still not at expert level though
0 u/ThisIsMyRealName 04 May 2019 05:32
That's C though.
0 u/Satirical [OP] 04 May 2019 05:59
bravo
0 u/boredTech 04 May 2019 13:46
it's not mine. (This is the 12 days of Christmas. Won an award on obfuscation. I still don't 100% know how it works.)
0 u/lili3 04 May 2019 06:54
have you heard of jsfuck? all JS code can be reduced down to 6 characters:
()[]!+I entered your solution and while it only used 6 characters, it did so 114,000 times hahaha
0 u/Satirical [OP] 04 May 2019 07:06
Well, lowest character count then, if we're being pedantic :^)
0 u/rcb 04 May 2019 08:35
Like this?
0 u/RevanProdigalKnight 20 May 2019 03:46
I'm a few
daysweeks late to the party, but you can actually accomplish the same in fewer characters.First, in your current solution, the
cvariable is completely unused, so it can be stripped.Result:
That strips
(4 + 9 + 4) = 17characters from the solution without affecting the output. But we can still do better.4000000 === 4e6, which strips a further 4 characters.So far we're down 21 characters, but there's still more we can strip. In JS, we can replace
ifstatements with truthy conditions using&&. Now, we can't replace the outerif/elseblock with this, and a ternary causes a syntax error, but the innerifstatement can be replaced. Unfortunately,x%2===0&&s+=xalso causes a ReferenceError to be thrown, because the left hand side of that statement is evaluated asx%2==0&&s. This means we must wraps+=xin parentheses, and we have saved no characters. Fortunately, anifstatements with a falsy condition can be replaced with||, which allows the much shorter overall syntax ofx%2||(s+=x). This saves us another 6 characters.With the new inner statement, we can also omit the curly braces and simply separate the
ifand theelsewith a semicolon, which saves us one more character, and we can also omit the semicolon after thebreakstatement at the end for one last character. This brings us to a total savings of 29 characters, resulting in the final solution of: