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

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

     1 /*
     2  * Any copyright is dedicated to the Public Domain.
     3  * http://creativecommons.org/licenses/publicdomain/
     4  */
     6 // Some simple testing of new, eval and some string stuff.
     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 }
    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 = [];
    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 }
    44 print("\nA number is 'perfect' if it is equal to the sum of its")
    45 print("divisors (excluding itself).\n");
    47 reportCompare(perfect(500).join(), "6,28,496");

mercurial