Algorithms.js – Atwood's Law applied to CS101
github.com
github.com
I noticed the following code:
while (b !== 0) { if (a > b) { a -= b; } else { b -= a; } }
This uses repeated subtraction (a -= b) to implement division with remainder (a %= b); imagine a=1e12+1, b=2.Please don't do this in your code. If there is a built it instruction for division with remainder, don't reimplement it poorly in javascript.
34 var tmp = a;
35 a = Math.max(a, b);
36 b = Math.min(tmp, b);
37 if (a % b === 0) return b;
to avoid the unnecessary repetitions if b is already the GCDEdit: Also, if you stick to the original subtraction-based version of the algorithm, why adding that other optimization? That wasn't part of the original algorithm, either. This seems to be double standard.
gcd(a, b) = gcd(b, a mod b),
and there is no need to compute mod with anything other than %.https://github.com/felipernb/algorithms.js/commit/e5a04f9ad0...
I'm surprised the author didn't implement the binary gcd, however, although it has the same big-O as Euclid: https://en.wikipedia.org/wiki/Binary_GCD_algorithm
I did a similar exercise when I was doing a course on Coursera in Python - https://github.com/prakhar1989/Algorithms
One cool feature of the site is that you can vote on solutions; this lets you see a lot of neat solutions to problems, and learn a lot about how to write clean code.
"Atwood's Law: any application that can be written in JavaScript, will eventually be written in JavaScript."
It's kind of a joke thing.
From the wiki (https://github.com/felipernb/algorithms.js/wiki):
The intention is to blend academic concepts with the
JavaScript bits of insanity, applying Atwood's Law to CS101.The javascript solution presented does everything in O(n) arithmetic operations, and the SICP way does it in O(ln(n)) arithmetic operations (actually, there are a lot of ways to do it in O(ln(n)) operations).
I mean, if we're going to screw around with the Os let's do it properly.
Example:
P: Look I have a spinning cube in 3d at 30 FPS!
HN: OMG, awesome, never done before!