|
1 /* |
|
2 * Any copyright is dedicated to the Public Domain. |
|
3 * http://creativecommons.org/licenses/publicdomain/ |
|
4 */ |
|
5 |
|
6 // Some simple testing of new, eval and some string stuff. |
|
7 |
|
8 // constructor -- expression array initialization |
|
9 function ExprArray(n,v) |
|
10 { |
|
11 // Initializes n values to v coerced to a string. |
|
12 for (var i = 0; i < n; i++) { |
|
13 this[i] = "" + v; |
|
14 } |
|
15 } |
|
16 |
|
17 |
|
18 // Print the perfect numbers up to n and the sum expression for n's divisors. |
|
19 function perfect(n) |
|
20 { |
|
21 print("The perfect numbers up to " + n + " are:"); |
|
22 var results = []; |
|
23 |
|
24 // We build sumOfDivisors[i] to hold a string expression for |
|
25 // the sum of the divisors of i, excluding i itself. |
|
26 var sumOfDivisors = new ExprArray(n+1,1); |
|
27 for (var divisor = 2; divisor <= n; divisor++) { |
|
28 for (var j = divisor + divisor; j <= n; j += divisor) { |
|
29 sumOfDivisors[j] += " + " + divisor; |
|
30 } |
|
31 // At this point everything up to 'divisor' has its sumOfDivisors |
|
32 // expression calculated, so we can determine whether it's perfect |
|
33 // already by evaluating. |
|
34 if (eval(sumOfDivisors[divisor]) == divisor) { |
|
35 print("" + divisor + " = " + sumOfDivisors[divisor]); |
|
36 results.push(divisor); |
|
37 } |
|
38 } |
|
39 print("That's all."); |
|
40 return results; |
|
41 } |
|
42 |
|
43 |
|
44 print("\nA number is 'perfect' if it is equal to the sum of its") |
|
45 print("divisors (excluding itself).\n"); |
|
46 |
|
47 reportCompare(perfect(500).join(), "6,28,496"); |