Merge mozilla-central into tracemonkey.
[mozilla-central.git] / js / src / perfect.js
blobaeca121186bfd0941734ae8d945ffee952ac0324
1 // Some simple testing of new, eval and some string stuff.
3 // constructor -- expression array initialization
4 function ExprArray(n,v)
6     // Initializes n values to v coerced to a string.
7     for (var i = 0; i < n; i++) {
8         this[i] = "" + v;
9     }
13 // Print the perfect numbers up to n and the sum expression for n's divisors.
14 function perfect(n)
16     print("The perfect numbers up to " +  n + " are:");
18     // We build sumOfDivisors[i] to hold a string expression for
19     // the sum of the divisors of i, excluding i itself.
20     var sumOfDivisors = new ExprArray(n+1,1);
21     for (var divisor = 2; divisor <= n; divisor++) {
22         for (var j = divisor + divisor; j <= n; j += divisor) {
23             sumOfDivisors[j] += " + " + divisor;
24         }
25         // At this point everything up to 'divisor' has its sumOfDivisors
26         // expression calculated, so we can determine whether it's perfect
27         // already by evaluating.
28         if (eval(sumOfDivisors[divisor]) == divisor) {
29             print("" + divisor + " = " + sumOfDivisors[divisor]);
30         }
31     }
32     print("That's all.");
36 print("\nA number is 'perfect' if it is equal to the sum of its")
37 print("divisors (excluding itself).\n");
38 perfect(500);