]> code.delx.au - gnu-emacs-elpa/blob - packages/realgud/test/node_modules/gcd.js/gcd.js
6d7ce32587ca42d10a016781509c1ec99532a28f
[gnu-emacs-elpa] / packages / realgud / test / node_modules / gcd.js / gcd.js
1 //!/usr/bin/env node
2 var util = require("util");
3 require("console");
4
5 function ask(question, format, callback) {
6 var stdin = process.stdin, stdout = process.stdout;
7
8 stdin.resume();
9 stdout.write(question + ": ");
10
11 stdin.once('data', function(data) {
12 data = data.toString().trim();
13
14 if (format.test(data)) {
15 callback(data);
16 } else {
17 stdout.write("It should match: "+ format +"\n");
18 ask(question, format, callback);
19 }
20 });
21 }
22
23 // GCD. We assume positive numbers
24 function gcd(a, b) {
25 // Make: a <= b
26 if (a > b) {
27 var temp = a;
28 a = b;
29 b = temp;
30 }
31
32 if (a <= 0) { return null };
33
34 if (a == 1 || b-a == 0) {
35 return a;
36 }
37 return gcd(b-a, a);
38 }
39
40 var a=24;
41
42 ask("GCD of 24 and", /^\d+$/, function(b_str) {
43 var b = parseInt(b_str, 10);
44 console.log(util.format("The GCD of %d and %d is %d", a, b,
45 gcd(a, b)));
46 process.exit();
47 });