File: perfect.js

package info (click to toggle)
mongodb 1%3A2.0.6-1.1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 17,204 kB
  • sloc: cpp: 109,783; ansic: 101,073; python: 2,287; perl: 395; makefile: 370; sh: 242; asm: 46
file content (39 lines) | stat: -rw-r--r-- 1,163 bytes parent folder | download | duplicates (24)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Some simple testing of new, eval and some string stuff.

// constructor -- expression array initialization
function ExprArray(n,v)
{
    // Initializes n values to v coerced to a string.
    for (var i = 0; i < n; i++) {
	this[i] = "" + v;
    }
}


// Print the perfect numbers up to n and the sum expression for n's divisors.
function perfect(n)
{
    print("The perfect numbers up to " +  n + " are:");

    // We build sumOfDivisors[i] to hold a string expression for
    // the sum of the divisors of i, excluding i itself.
    var sumOfDivisors = new ExprArray(n+1,1);
    for (var divisor = 2; divisor <= n; divisor++) {
	for (var j = divisor + divisor; j <= n; j += divisor) {
	    sumOfDivisors[j] += " + " + divisor;
	}
	// At this point everything up to 'divisor' has its sumOfDivisors
	// expression calculated, so we can determine whether it's perfect
	// already by evaluating.
	if (eval(sumOfDivisors[divisor]) == divisor) {
	    print("" + divisor + " = " + sumOfDivisors[divisor]);
	}
    }
    print("That's all.");
}


print("\nA number is 'perfect' if it is equal to the sum of its")
print("divisors (excluding itself).\n");
perfect(500);