michael@0: /* michael@0: * Any copyright is dedicated to the Public Domain. michael@0: * http://creativecommons.org/licenses/publicdomain/ michael@0: */ michael@0: michael@0: // Some simple testing of new, eval and some string stuff. michael@0: michael@0: // constructor -- expression array initialization michael@0: function ExprArray(n,v) michael@0: { michael@0: // Initializes n values to v coerced to a string. michael@0: for (var i = 0; i < n; i++) { michael@0: this[i] = "" + v; michael@0: } michael@0: } michael@0: michael@0: michael@0: // Print the perfect numbers up to n and the sum expression for n's divisors. michael@0: function perfect(n) michael@0: { michael@0: print("The perfect numbers up to " + n + " are:"); michael@0: var results = []; michael@0: michael@0: // We build sumOfDivisors[i] to hold a string expression for michael@0: // the sum of the divisors of i, excluding i itself. michael@0: var sumOfDivisors = new ExprArray(n+1,1); michael@0: for (var divisor = 2; divisor <= n; divisor++) { michael@0: for (var j = divisor + divisor; j <= n; j += divisor) { michael@0: sumOfDivisors[j] += " + " + divisor; michael@0: } michael@0: // At this point everything up to 'divisor' has its sumOfDivisors michael@0: // expression calculated, so we can determine whether it's perfect michael@0: // already by evaluating. michael@0: if (eval(sumOfDivisors[divisor]) == divisor) { michael@0: print("" + divisor + " = " + sumOfDivisors[divisor]); michael@0: results.push(divisor); michael@0: } michael@0: } michael@0: print("That's all."); michael@0: return results; michael@0: } michael@0: michael@0: michael@0: print("\nA number is 'perfect' if it is equal to the sum of its") michael@0: print("divisors (excluding itself).\n"); michael@0: michael@0: reportCompare(perfect(500).join(), "6,28,496");