Perfect numbers: Difference between revisions
(Added Ada) |
(Added J solution.) |
||
Line 32: | Line 32: | ||
END IF |
END IF |
||
END FUNCTION</qbasic> |
END FUNCTION</qbasic> |
||
=={{header|J}}== |
|||
is_perfect=: = [: +/ ((0=]|[)i.) # i. |
|||
The program defined above, like programs found here in other languages, assumes that the input will be a scalar positive integer. |
|||
Examples of use, including extensions beyond those assumptions: |
|||
is_perfect 33550336 |
|||
1 |
|||
}.I. is_perfect"0 i. 10000 |
|||
6 28 496 8128 |
|||
] zero_through_twentynine =. i. 3 10 |
|||
0 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 |
|||
is_pos_int=: 0&< *. ]=>. |
|||
(is_perfect"0 *. is_pos_int) zero_through_twentynine |
|||
0 0 0 0 0 0 1 0 0 0 |
|||
0 0 0 0 0 0 0 0 0 0 |
|||
0 0 0 0 0 0 0 0 1 0 |
|||
=={{header|Java}}== |
=={{header|Java}}== |
Revision as of 04:05, 24 August 2008
You are encouraged to solve this task according to the task description, using any language you may know.
Write a function which says whether a number is perfect.
A number is perfect if the sum of its factors is equal to twice the number. An equivalent condition is that n is perfect if the sum of n's factors that are less than n is equal to n.
Ada
<Ada> function Is_Perfect(N : Positive) return Boolean is
Sum : Natural := 0;
begin
for I in 1..N - 1 loop if N mod I = 0 then Sum := Sum + I; end if; end loop; return Sum = N;
end Is_Perfect; </Ada>
BASIC
<qbasic>FUNCTION perf(n) sum = 0 for i = 1 to n - 1 IF n MOD i = 0 THEN sum = sum + i END IF NEXT i IF sum = n THEN perf = 1 ELSE perf = 0 END IF END FUNCTION</qbasic>
J
is_perfect=: = [: +/ ((0=]|[)i.) # i.
The program defined above, like programs found here in other languages, assumes that the input will be a scalar positive integer.
Examples of use, including extensions beyond those assumptions:
is_perfect 33550336 1 }.I. is_perfect"0 i. 10000 6 28 496 8128 ] zero_through_twentynine =. i. 3 10 0 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 is_pos_int=: 0&< *. ]=>. (is_perfect"0 *. is_pos_int) zero_through_twentynine 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0
Java
<java>public static boolean perf(int n){ int sum= 0; for(int i= 1;i < n;i++){ if(n % i == 0){ sum+= i; } } return sum == n; }</java> Or for arbitrary precision: <java>import java.math.BigInteger;
public static boolean perf(BigInteger n){ BigInteger sum= BigInteger.ZERO; for(BigInteger i= BigInteger.ONE; i.compareTo(n) < 0;i=i.add(BigInteger.ONE)){ if(n.mod(i).compareTo(BigInteger.ZERO) == 0){ sum= sum.add(i); } } return sum.compareTo(n) == 0; }</java>
Python
<python>def perf(n):
sum = 0 for i in xrange(1,n): if n % i == 0: sum += i return sum == n</python>
Using functional form <python>def perf(n):
return n == sum( i for i in xrange(1,n) if n % i == 0)</python>