js/src/tests/js1_1/regress/perfect.js

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/js/src/tests/js1_1/regress/perfect.js	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,47 @@
     1.4 +/*
     1.5 + * Any copyright is dedicated to the Public Domain.
     1.6 + * http://creativecommons.org/licenses/publicdomain/
     1.7 + */
     1.8 +
     1.9 +// Some simple testing of new, eval and some string stuff.
    1.10 +
    1.11 +// constructor -- expression array initialization
    1.12 +function ExprArray(n,v)
    1.13 +{
    1.14 +    // Initializes n values to v coerced to a string.
    1.15 +    for (var i = 0; i < n; i++) {
    1.16 +	this[i] = "" + v;
    1.17 +    }
    1.18 +}
    1.19 +
    1.20 +
    1.21 +// Print the perfect numbers up to n and the sum expression for n's divisors.
    1.22 +function perfect(n)
    1.23 +{
    1.24 +    print("The perfect numbers up to " +  n + " are:");
    1.25 +    var results = [];
    1.26 +
    1.27 +    // We build sumOfDivisors[i] to hold a string expression for
    1.28 +    // the sum of the divisors of i, excluding i itself.
    1.29 +    var sumOfDivisors = new ExprArray(n+1,1);
    1.30 +    for (var divisor = 2; divisor <= n; divisor++) {
    1.31 +	for (var j = divisor + divisor; j <= n; j += divisor) {
    1.32 +	    sumOfDivisors[j] += " + " + divisor;
    1.33 +	}
    1.34 +	// At this point everything up to 'divisor' has its sumOfDivisors
    1.35 +	// expression calculated, so we can determine whether it's perfect
    1.36 +	// already by evaluating.
    1.37 +	if (eval(sumOfDivisors[divisor]) == divisor) {
    1.38 +	    print("" + divisor + " = " + sumOfDivisors[divisor]);
    1.39 +	    results.push(divisor);
    1.40 +	}
    1.41 +    }
    1.42 +    print("That's all.");
    1.43 +    return results;
    1.44 +}
    1.45 +
    1.46 +
    1.47 +print("\nA number is 'perfect' if it is equal to the sum of its")
    1.48 +print("divisors (excluding itself).\n");
    1.49 +
    1.50 +reportCompare(perfect(500).join(), "6,28,496");

mercurial