Perfect numbers: Difference between revisions

Content added Content deleted
No edit summary
m (syntax highlighting fixup automation)
Line 27: Line 27:
{{trans|Python}}
{{trans|Python}}


<lang 11l>F perf(n)
<syntaxhighlight lang="11l">F perf(n)
V sum = 0
V sum = 0
L(i) 1 .< n
L(i) 1 .< n
Line 36: Line 36:
L(i) 1..10000
L(i) 1..10000
I perf(i)
I perf(i)
print(i, end' ‘ ’)</lang>
print(i, end' ‘ ’)</syntaxhighlight>


{{out}}
{{out}}
Line 50: Line 50:
The only added optimization is the loop up to n/2 instead of n-1.
The only added optimization is the loop up to n/2 instead of n-1.
With 31 bit integers the limit is 2,147,483,647.
With 31 bit integers the limit is 2,147,483,647.
<lang 360asm>* Perfect numbers 15/05/2016
<syntaxhighlight lang="360asm">* Perfect numbers 15/05/2016
PERFECTN CSECT
PERFECTN CSECT
USING PERFECTN,R13 prolog
USING PERFECTN,R13 prolog
Line 96: Line 96:
PG DC CL12' ' buffer
PG DC CL12' ' buffer
YREGS
YREGS
END PERFECTN</lang>
END PERFECTN</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 108: Line 108:
Use of optimizations found in Rexx algorithms and use of packed decimal to have bigger numbers.
Use of optimizations found in Rexx algorithms and use of packed decimal to have bigger numbers.
With 15 digit decimal integers the limit is 999,999,999,999,999.
With 15 digit decimal integers the limit is 999,999,999,999,999.
<lang 360asm>* Perfect numbers 15/05/2016
<syntaxhighlight lang="360asm">* Perfect numbers 15/05/2016
PERFECPO CSECT
PERFECPO CSECT
USING PERFECPO,R13 prolog
USING PERFECPO,R13 prolog
Line 183: Line 183:
PW2 DS PL16
PW2 DS PL16
YREGS
YREGS
END PERFECPO</lang>
END PERFECPO</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 197: Line 197:
=={{header|AArch64 Assembly}}==
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program perfectNumber64.s */
/* program perfectNumber64.s */
Line 458: Line 458:
/* for this file see task include a file in language AArch64 assembly */
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
<pre>
<pre>
Perfect : 6
Perfect : 6
Line 471: Line 471:
</pre>
</pre>
=={{header|Action!}}==
=={{header|Action!}}==
<lang Action!>PROC Main()
<syntaxhighlight lang="action!">PROC Main()
DEFINE MAXNUM="10000"
DEFINE MAXNUM="10000"
CARD ARRAY pds(MAXNUM+1)
CARD ARRAY pds(MAXNUM+1)
Line 494: Line 494:
FI
FI
OD
OD
RETURN</lang>
RETURN</syntaxhighlight>
{{out}}
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Perfect_numbers.png Screenshot from Atari 8-bit computer]
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Perfect_numbers.png Screenshot from Atari 8-bit computer]
Line 505: Line 505:


=={{header|Ada}}==
=={{header|Ada}}==
<lang ada>function Is_Perfect(N : Positive) return Boolean is
<syntaxhighlight lang="ada">function Is_Perfect(N : Positive) return Boolean is
Sum : Natural := 0;
Sum : Natural := 0;
begin
begin
Line 514: Line 514:
end loop;
end loop;
return Sum = N;
return Sum = N;
end Is_Perfect;</lang>
end Is_Perfect;</syntaxhighlight>


=={{header|ALGOL 60}}==
=={{header|ALGOL 60}}==
{{works with|A60}}
{{works with|A60}}
<lang algol60>
<syntaxhighlight lang="algol60">
begin
begin


Line 562: Line 562:


end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 574: Line 574:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
{{works with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d]}}
<lang algol68>PROC is perfect = (INT candidate)BOOL: (
<syntaxhighlight lang="algol68">PROC is perfect = (INT candidate)BOOL: (
INT sum :=1;
INT sum :=1;
FOR f1 FROM 2 TO ENTIER ( sqrt(candidate)*(1+2*small real) ) WHILE
FOR f1 FROM 2 TO ENTIER ( sqrt(candidate)*(1+2*small real) ) WHILE
Line 594: Line 594:
IF is perfect(i) THEN print((i, new line)) FI
IF is perfect(i) THEN print((i, new line)) FI
OD
OD
)</lang>
)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 606: Line 606:
=={{header|ALGOL W}}==
=={{header|ALGOL W}}==
Based on the Algol 68 version.
Based on the Algol 68 version.
<lang algolw>begin
<syntaxhighlight lang="algolw">begin
% returns true if n is perfect, false otherwise %
% returns true if n is perfect, false otherwise %
% n must be > 0 %
% n must be > 0 %
Line 627: Line 627:
% test isPerfect %
% test isPerfect %
for n := 2 until 10000 do if isPerfect( n ) then write( n );
for n := 2 until 10000 do if isPerfect( n ) then write( n );
end.</lang>
end.</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 639: Line 639:
===Functional===
===Functional===
{{Trans|JavaScript}}
{{Trans|JavaScript}}
<lang AppleScript>-- PERFECT NUMBERS -----------------------------------------------------------
<syntaxhighlight lang="applescript">-- PERFECT NUMBERS -----------------------------------------------------------


-- perfect :: integer -> bool
-- perfect :: integer -> bool
Line 746: Line 746:
end script
end script
end if
end if
end mReturn</lang>
end mReturn</syntaxhighlight>
{{Out}}
{{Out}}
<lang AppleScript>{6, 28, 496, 8128}</lang>
<syntaxhighlight lang="applescript">{6, 28, 496, 8128}</syntaxhighlight>
----
----
===Idiomatic===
===Idiomatic===
====Sum of proper divisors====
====Sum of proper divisors====
<lang applescript>on aliquotSum(n)
<syntaxhighlight lang="applescript">on aliquotSum(n)
if (n < 2) then return 0
if (n < 2) then return 0
set sum to 1
set sum to 1
Line 783: Line 783:
if (isPerfect(n)) then set end of output to n
if (isPerfect(n)) then set end of output to n
end repeat
end repeat
return output</lang>
return output</syntaxhighlight>


{{output}}
{{output}}
<lang applescript>{6, 28, 496, 8128}</lang>
<syntaxhighlight lang="applescript">{6, 28, 496, 8128}</syntaxhighlight>


====Euclid====
====Euclid====
<lang applescript>on isPerfect(n)
<syntaxhighlight lang="applescript">on isPerfect(n)
-- All the known perfect numbers listed in Wikipedia end with either 6 or 28.
-- All the known perfect numbers listed in Wikipedia end with either 6 or 28.
-- These endings are either preceded by odd digits or are the numbers themselves.
-- These endings are either preceded by odd digits or are the numbers themselves.
Line 813: Line 813:
if (isPerfect(n)) then set end of output to n
if (isPerfect(n)) then set end of output to n
end repeat
end repeat
return output</lang>
return output</syntaxhighlight>


{{output}}
{{output}}
<lang applescript>{6, 28, 496, 8128, 33550336}</lang>
<syntaxhighlight lang="applescript">{6, 28, 496, 8128, 33550336}</syntaxhighlight>


====Practical====
====Practical====
But since AppleScript can only physically manage seven of the known perfect numbers, they may as well be in a look-up list for maximum efficiency:
But since AppleScript can only physically manage seven of the known perfect numbers, they may as well be in a look-up list for maximum efficiency:


<lang applescript>on isPerfect(n)
<syntaxhighlight lang="applescript">on isPerfect(n)
if (n > 1.37438691328E+11) then return missing value -- Too high for perfection to be determinable.
if (n > 1.37438691328E+11) then return missing value -- Too high for perfection to be determinable.
return (n is in {6, 28, 496, 8128, 33550336, 8.589869056E+9, 1.37438691328E+11})
return (n is in {6, 28, 496, 8128, 33550336, 8.589869056E+9, 1.37438691328E+11})
end isPerfect</lang>
end isPerfect</syntaxhighlight>


=={{header|ARM Assembly}}==
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>


/* ARM assembly Raspberry PI */
/* ARM assembly Raspberry PI */
Line 904: Line 904:
/***************************************************/
/***************************************************/
.include "../affichage.inc"
.include "../affichage.inc"
</syntaxhighlight>
</lang>
<pre>
<pre>
Perfect : 6
Perfect : 6
Line 913: Line 913:
</pre>
</pre>
=={{header|Arturo}}==
=={{header|Arturo}}==
<lang rebol>divisors: $[n][ select 1..(n/2)+1 'i -> 0 = n % i ]
<syntaxhighlight lang="rebol">divisors: $[n][ select 1..(n/2)+1 'i -> 0 = n % i ]
perfect?: $[n][ n = sum divisors n ]
perfect?: $[n][ n = sum divisors n ]
loop 2..1000 'i [
loop 2..1000 'i [
if perfect? i -> print i
if perfect? i -> print i
]</lang>
]</syntaxhighlight>


=={{header|AutoHotkey}}==
=={{header|AutoHotkey}}==
This will find the first 8 perfect numbers.
This will find the first 8 perfect numbers.
<lang autohotkey>Loop, 30 {
<syntaxhighlight lang="autohotkey">Loop, 30 {
If isMersennePrime(A_Index + 1)
If isMersennePrime(A_Index + 1)
res .= "Perfect number: " perfectNum(A_Index + 1) "`n"
res .= "Perfect number: " perfectNum(A_Index + 1) "`n"
Line 943: Line 943:
Return false
Return false
Return true
Return true
}</lang>
}</syntaxhighlight>


=={{header|AWK}}==
=={{header|AWK}}==
<lang awk>$ awk 'func perf(n){s=0;for(i=1;i<n;i++)if(n%i==0)s+=i;return(s==n)}
<syntaxhighlight lang="awk">$ awk 'func perf(n){s=0;for(i=1;i<n;i++)if(n%i==0)s+=i;return(s==n)}
BEGIN{for(i=1;i<10000;i++)if(perf(i))print i}'
BEGIN{for(i=1;i<10000;i++)if(perf(i))print i}'
6
6
28
28
496
496
8128</lang>
8128</syntaxhighlight>


=={{header|Axiom}}==
=={{header|Axiom}}==
{{trans|Mathematica}}
{{trans|Mathematica}}
Using the interpreter, define the function:
Using the interpreter, define the function:
<lang Axiom>perfect?(n:Integer):Boolean == reduce(+,divisors n) = 2*n</lang>
<syntaxhighlight lang="axiom">perfect?(n:Integer):Boolean == reduce(+,divisors n) = 2*n</syntaxhighlight>
Alternatively, using the Spad compiler:
Alternatively, using the Spad compiler:
<lang Axiom>)abbrev package TESTP TestPackage
<syntaxhighlight lang="axiom">)abbrev package TESTP TestPackage
TestPackage() : withma
TestPackage() : withma
perfect?: Integer -> Boolean
perfect?: Integer -> Boolean
Line 964: Line 964:
add
add
import IntegerNumberTheoryFunctions
import IntegerNumberTheoryFunctions
perfect? n == reduce("+",divisors n) = 2*n</lang>
perfect? n == reduce("+",divisors n) = 2*n</syntaxhighlight>


Examples (testing 496, testing 128, finding all perfect numbers in 1...10000):
Examples (testing 496, testing 128, finding all perfect numbers in 1...10000):
<lang Axiom>perfect? 496
<syntaxhighlight lang="axiom">perfect? 496
perfect? 128
perfect? 128
[i for i in 1..10000 | perfect? i]</lang>
[i for i in 1..10000 | perfect? i]</syntaxhighlight>
{{Out}}
{{Out}}
<lang Axiom>true
<syntaxhighlight lang="axiom">true
false
false
[6,28,496,8128]</lang>
[6,28,496,8128]</syntaxhighlight>


=={{header|BASIC}}==
=={{header|BASIC}}==
{{works with|QuickBasic|4.5}}
{{works with|QuickBasic|4.5}}
<lang qbasic>FUNCTION perf(n)
<syntaxhighlight lang="qbasic">FUNCTION perf(n)
sum = 0
sum = 0
for i = 1 to n - 1
for i = 1 to n - 1
Line 989: Line 989:
perf = 0
perf = 0
END IF
END IF
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>




==={{header|BASIC256}}===
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
{{trans|FreeBASIC}}
<syntaxhighlight lang="basic256">
<lang BASIC256>
function isPerfect(n)
function isPerfect(n)
if (n < 2) or (n mod 2 = 1) then return False
if (n < 2) or (n mod 2 = 1) then return False
Line 1,014: Line 1,014:
next i
next i
end
end
</syntaxhighlight>
</lang>




==={{header|IS-BASIC}}===
==={{header|IS-BASIC}}===
<lang IS-BASIC>100 PROGRAM "PerfectN.bas"
<syntaxhighlight lang="is-basic">100 PROGRAM "PerfectN.bas"
110 FOR X=1 TO 10000
110 FOR X=1 TO 10000
120 IF PERFECT(X) THEN PRINT X;
120 IF PERFECT(X) THEN PRINT X;
Line 1,029: Line 1,029:
190 NEXT
190 NEXT
200 LET PERFECT=N=S
200 LET PERFECT=N=S
210 END DEF</lang>
210 END DEF</syntaxhighlight>


==={{header|Sinclair ZX81 BASIC}}===
==={{header|Sinclair ZX81 BASIC}}===
Call this subroutine and it will (eventually) return <tt>PERFECT</tt> = 1 if <tt>N</tt> is perfect or <tt>PERFECT</tt> = 0 if it is not.
Call this subroutine and it will (eventually) return <tt>PERFECT</tt> = 1 if <tt>N</tt> is perfect or <tt>PERFECT</tt> = 0 if it is not.
<lang basic>2000 LET SUM=0
<syntaxhighlight lang="basic">2000 LET SUM=0
2010 FOR F=1 TO N-1
2010 FOR F=1 TO N-1
2020 IF N/F=INT (N/F) THEN LET SUM=SUM+F
2020 IF N/F=INT (N/F) THEN LET SUM=SUM+F
2030 NEXT F
2030 NEXT F
2040 LET PERFECT=SUM=N
2040 LET PERFECT=SUM=N
2050 RETURN</lang>
2050 RETURN</syntaxhighlight>


==={{header|True BASIC}}===
==={{header|True BASIC}}===
<lang basic>
<syntaxhighlight lang="basic">
FUNCTION perf(n)
FUNCTION perf(n)
IF n < 2 or ramainder(n,2) = 1 then LET perf = 0
IF n < 2 or ramainder(n,2) = 1 then LET perf = 0
Line 1,063: Line 1,063:
PRINT "Presione cualquier tecla para salir"
PRINT "Presione cualquier tecla para salir"
END
END
</syntaxhighlight>
</lang>


=={{header|BBC BASIC}}==
=={{header|BBC BASIC}}==
===BASIC version===
===BASIC version===
<lang bbcbasic> FOR n% = 2 TO 10000 STEP 2
<syntaxhighlight lang="bbcbasic"> FOR n% = 2 TO 10000 STEP 2
IF FNperfect(n%) PRINT n%
IF FNperfect(n%) PRINT n%
NEXT
NEXT
Line 1,079: Line 1,079:
NEXT
NEXT
IF I% = SQR(N%) S% += I%
IF I% = SQR(N%) S% += I%
= (N% = S%)</lang>
= (N% = S%)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,090: Line 1,090:
===Assembler version===
===Assembler version===
{{works with|BBC BASIC for Windows}}
{{works with|BBC BASIC for Windows}}
<lang bbcbasic> DIM P% 100
<syntaxhighlight lang="bbcbasic"> DIM P% 100
[OPT 2 :.S% xor edi,edi
[OPT 2 :.S% xor edi,edi
.perloop mov eax,ebx : cdq : div ecx : or edx,edx : loopnz perloop : inc ecx
.perloop mov eax,ebx : cdq : div ecx : or edx,edx : loopnz perloop : inc ecx
Line 1,099: Line 1,099:
IF B% = USRS% PRINT B%
IF B% = USRS% PRINT B%
NEXT
NEXT
END</lang>
END</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,111: Line 1,111:


=={{header|Bracmat}}==
=={{header|Bracmat}}==
<lang bracmat>( ( perf
<syntaxhighlight lang="bracmat">( ( perf
= sum i
= sum i
. 0:?sum
. 0:?sum
Line 1,128: Line 1,128:
& (perf$!n&out$!n|)
& (perf$!n&out$!n|)
)
)
);</lang>
);</syntaxhighlight>
{{Out}}
{{Out}}
<pre>6
<pre>6
Line 1,136: Line 1,136:


=={{header|Burlesque}}==
=={{header|Burlesque}}==
<lang burlesque>Jfc++\/2.*==</lang>
<syntaxhighlight lang="burlesque">Jfc++\/2.*==</syntaxhighlight>


<lang burlesque>blsq) 8200ro{Jfc++\/2.*==}f[
<syntaxhighlight lang="burlesque">blsq) 8200ro{Jfc++\/2.*==}f[


{6 28 496 8128}</lang>
{6 28 496 8128}</syntaxhighlight>


=={{header|C}}==
=={{header|C}}==
{{trans|D}}
{{trans|D}}
<lang c>#include "stdio.h"
<syntaxhighlight lang="c">#include "stdio.h"
#include "math.h"
#include "math.h"


Line 1,170: Line 1,170:


return 0;
return 0;
}</lang>
}</syntaxhighlight>
Using functions from [[Factors of an integer#Prime factoring]]:
Using functions from [[Factors of an integer#Prime factoring]]:
<lang c>int main()
<syntaxhighlight lang="c">int main()
{
{
int j;
int j;
Line 1,186: Line 1,186:
return 0;
return 0;
}</lang>
}</syntaxhighlight>


=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==
{{trans|C++}}
{{trans|C++}}
<lang csharp>static void Main(string[] args)
<syntaxhighlight lang="csharp">static void Main(string[] args)
{
{
Console.WriteLine("Perfect numbers from 1 to 33550337:");
Console.WriteLine("Perfect numbers from 1 to 33550337:");
Line 1,213: Line 1,213:


return sum == num ;
return sum == num ;
}</lang>
}</syntaxhighlight>
===Version using Lambdas, will only work from version 3 of C# on===
===Version using Lambdas, will only work from version 3 of C# on===
<lang csharp>static void Main(string[] args)
<syntaxhighlight lang="csharp">static void Main(string[] args)
{
{
Console.WriteLine("Perfect numbers from 1 to 33550337:");
Console.WriteLine("Perfect numbers from 1 to 33550337:");
Line 1,231: Line 1,231:
{
{
return Enumerable.Range(1, num - 1).Sum(n => num % n == 0 ? n : 0 ) == num;
return Enumerable.Range(1, num - 1).Sum(n => num % n == 0 ? n : 0 ) == num;
}</lang>
}</syntaxhighlight>


=={{header|C++}}==
=={{header|C++}}==
{{works with|gcc}}
{{works with|gcc}}
<lang cpp>#include <iostream>
<syntaxhighlight lang="cpp">#include <iostream>
using namespace std ;
using namespace std ;


Line 1,254: Line 1,254:
return 0 ;
return 0 ;
}
}
</syntaxhighlight>
</lang>


=={{header|Clojure}}==
=={{header|Clojure}}==
<lang clojure>(defn proper-divisors [n]
<syntaxhighlight lang="clojure">(defn proper-divisors [n]
(if (< n 4)
(if (< n 4)
[1]
[1]
Line 1,265: Line 1,265:


(defn perfect? [n]
(defn perfect? [n]
(= (reduce + (proper-divisors n)) n))</lang>
(= (reduce + (proper-divisors n)) n))</syntaxhighlight>


{{trans|Haskell}}
{{trans|Haskell}}
<lang clojure>(defn perfect? [n]
<syntaxhighlight lang="clojure">(defn perfect? [n]
(->> (for [i (range 1 n)] :when (zero? (rem n i))] i)
(->> (for [i (range 1 n)] :when (zero? (rem n i))] i)
(reduce +)
(reduce +)
(= n)))</lang>
(= n)))</syntaxhighlight>


===Functional version===
===Functional version===
<lang clojure>(defn perfect? [n]
<syntaxhighlight lang="clojure">(defn perfect? [n]
(= (reduce + (filter #(zero? (rem n %)) (range 1 n))) n))</lang>
(= (reduce + (filter #(zero? (rem n %)) (range 1 n))) n))</syntaxhighlight>


=={{header|COBOL}}==
=={{header|COBOL}}==
Line 1,281: Line 1,281:
{{works with|Visual COBOL}}
{{works with|Visual COBOL}}
main.cbl:
main.cbl:
<lang cobol> $set REPOSITORY "UPDATE ON"
<syntaxhighlight lang="cobol"> $set REPOSITORY "UPDATE ON"
IDENTIFICATION DIVISION.
IDENTIFICATION DIVISION.
Line 1,304: Line 1,304:
GOBACK
GOBACK
.
.
END PROGRAM perfect-main.</lang>
END PROGRAM perfect-main.</syntaxhighlight>


perfect.cbl:
perfect.cbl:
<lang cobol> IDENTIFICATION DIVISION.
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
FUNCTION-ID. perfect.
FUNCTION-ID. perfect.
Line 1,343: Line 1,343:
GOBACK
GOBACK
.
.
END FUNCTION perfect.</lang>
END FUNCTION perfect.</syntaxhighlight>


=={{header|CoffeeScript}}==
=={{header|CoffeeScript}}==
Optimized version, for fun.
Optimized version, for fun.
<lang coffeescript>is_perfect_number = (n) ->
<syntaxhighlight lang="coffeescript">is_perfect_number = (n) ->
do_factors_add_up_to n, 2*n
do_factors_add_up_to n, 2*n
Line 1,395: Line 1,395:
for n in known_perfects
for n in known_perfects
throw Error("fail") unless is_perfect_number(n)
throw Error("fail") unless is_perfect_number(n)
throw Error("fail") if is_perfect_number(n+1)</lang>
throw Error("fail") if is_perfect_number(n+1)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,407: Line 1,407:
=={{header|Common Lisp}}==
=={{header|Common Lisp}}==
{{trans|Haskell}}
{{trans|Haskell}}
<lang lisp>(defun perfectp (n)
<syntaxhighlight lang="lisp">(defun perfectp (n)
(= n (loop for i from 1 below n when (= 0 (mod n i)) sum i)))</lang>
(= n (loop for i from 1 below n when (= 0 (mod n i)) sum i)))</syntaxhighlight>


=={{header|D}}==
=={{header|D}}==
===Functional Version===
===Functional Version===
<lang d>import std.stdio, std.algorithm, std.range;
<syntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;


bool isPerfectNumber1(in uint n) pure nothrow
bool isPerfectNumber1(in uint n) pure nothrow
Line 1,423: Line 1,423:
void main() {
void main() {
iota(1, 10_000).filter!isPerfectNumber1.writeln;
iota(1, 10_000).filter!isPerfectNumber1.writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[6, 28, 496, 8128]</pre>
<pre>[6, 28, 496, 8128]</pre>
Line 1,429: Line 1,429:
===Faster Imperative Version===
===Faster Imperative Version===
{{trans|Algol}}
{{trans|Algol}}
<lang d>import std.stdio, std.math, std.range, std.algorithm;
<syntaxhighlight lang="d">import std.stdio, std.math, std.range, std.algorithm;


bool isPerfectNumber2(in int n) pure nothrow {
bool isPerfectNumber2(in int n) pure nothrow {
Line 1,449: Line 1,449:
void main() {
void main() {
10_000.iota.filter!isPerfectNumber2.writeln;
10_000.iota.filter!isPerfectNumber2.writeln;
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>[6, 28, 496, 8128]</pre>
<pre>[6, 28, 496, 8128]</pre>
Line 1,457: Line 1,457:
=={{header|Dart}}==
=={{header|Dart}}==
=== Explicit Iterative Version ===
=== Explicit Iterative Version ===
<lang d>/*
<syntaxhighlight lang="d">/*
* Function to test if a number is a perfect number
* Function to test if a number is a perfect number
* A number is a perfect number if it is equal to the sum of all its divisors
* A number is a perfect number if it is equal to the sum of all its divisors
Line 1,479: Line 1,479:
// We return the test if n is equal to sumOfDivisors
// We return the test if n is equal to sumOfDivisors
return n == sumOfDivisors;
return n == sumOfDivisors;
}</lang>
}</syntaxhighlight>


=== Compact Version ===
=== Compact Version ===
{{trans|Julia}}
{{trans|Julia}}
<lang d>isPerfect(n) =>
<syntaxhighlight lang="d">isPerfect(n) =>
n == new List.generate(n-1, (i) => n%(i+1) == 0 ? i+1 : 0).fold(0, (p,n)=>p+n);</lang>
n == new List.generate(n-1, (i) => n%(i+1) == 0 ? i+1 : 0).fold(0, (p,n)=>p+n);</syntaxhighlight>


In either case, if we test to find all the perfect numbers up to 1000, we get:
In either case, if we test to find all the perfect numbers up to 1000, we get:
<lang d>main() =>
<syntaxhighlight lang="d">main() =>
new List.generate(1000,(i)=>i+1).where(isPerfect).forEach(print);</lang>
new List.generate(1000,(i)=>i+1).where(isPerfect).forEach(print);</syntaxhighlight>
{{out}}
{{out}}
<pre>6
<pre>6
Line 1,497: Line 1,497:
=={{header|Dyalect}}==
=={{header|Dyalect}}==


<lang dyalect>func isPerfect(num) {
<syntaxhighlight lang="dyalect">func isPerfect(num) {
var sum = 0
var sum = 0
for i in 1..<num {
for i in 1..<num {
Line 1,517: Line 1,517:
print("\(x) is perfect")
print("\(x) is perfect")
}
}
}</lang>
}</syntaxhighlight>


=={{header|E}}==
=={{header|E}}==
<lang e>pragma.enable("accumulator")
<syntaxhighlight lang="e">pragma.enable("accumulator")
def isPerfectNumber(x :int) {
def isPerfectNumber(x :int) {
var sum := 0
var sum := 0
Line 1,528: Line 1,528:
}
}
return sum <=> x
return sum <=> x
}</lang>
}</syntaxhighlight>


=={{header|Eiffel}}==
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
class
APPLICATION
APPLICATION
Line 1,573: Line 1,573:


end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 1,584: Line 1,584:
=={{header|Elena}}==
=={{header|Elena}}==
ELENA 4.x:
ELENA 4.x:
<lang elena>import system'routines;
<syntaxhighlight lang="elena">import system'routines;
import system'math;
import system'math;
import extensions;
import extensions;
Line 1,603: Line 1,603:
console.readChar()
console.readChar()
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 1,613: Line 1,613:


=={{header|Elixir}}==
=={{header|Elixir}}==
<lang elixir>defmodule RC do
<syntaxhighlight lang="elixir">defmodule RC do
def is_perfect(1), do: false
def is_perfect(1), do: false
def is_perfect(n) when n > 1 do
def is_perfect(n) when n > 1 do
Line 1,625: Line 1,625:
end
end


IO.inspect (for i <- 1..10000, RC.is_perfect(i), do: i)</lang>
IO.inspect (for i <- 1..10000, RC.is_perfect(i), do: i)</syntaxhighlight>


{{out}}
{{out}}
Line 1,633: Line 1,633:


=={{header|Erlang}}==
=={{header|Erlang}}==
<lang erlang>is_perfect(X) ->
<syntaxhighlight lang="erlang">is_perfect(X) ->
X == lists:sum([N || N <- lists:seq(1,X-1), X rem N == 0]).</lang>
X == lists:sum([N || N <- lists:seq(1,X-1), X rem N == 0]).</syntaxhighlight>


=={{header|ERRE}}==
=={{header|ERRE}}==
<lang ERRE>PROGRAM PERFECT
<syntaxhighlight lang="erre">PROGRAM PERFECT


PROCEDURE PERFECT(N%->OK%)
PROCEDURE PERFECT(N%->OK%)
Line 1,655: Line 1,655:
IF OK% THEN PRINT(N%)
IF OK% THEN PRINT(N%)
END FOR
END FOR
END PROGRAM</lang>
END PROGRAM</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,665: Line 1,665:


=={{header|F_Sharp|F#}}==
=={{header|F_Sharp|F#}}==
<lang fsharp>let perf n = n = List.fold (+) 0 (List.filter (fun i -> n % i = 0) [1..(n-1)])
<syntaxhighlight lang="fsharp">let perf n = n = List.fold (+) 0 (List.filter (fun i -> n % i = 0) [1..(n-1)])


for i in 1..10000 do if (perf i) then printfn "%i is perfect" i</lang>
for i in 1..10000 do if (perf i) then printfn "%i is perfect" i</syntaxhighlight>
{{Out}}
{{Out}}
<pre>6 is perfect
<pre>6 is perfect
Line 1,675: Line 1,675:


=={{header|Factor}}==
=={{header|Factor}}==
<lang factor>USING: kernel math math.primes.factors sequences ;
<syntaxhighlight lang="factor">USING: kernel math math.primes.factors sequences ;
IN: rosettacode.perfect-numbers
IN: rosettacode.perfect-numbers


: perfect? ( n -- ? ) [ divisors sum ] [ 2 * ] bi = ;</lang>
: perfect? ( n -- ? ) [ divisors sum ] [ 2 * ] bi = ;</syntaxhighlight>


=={{header|FALSE}}==
=={{header|FALSE}}==
<lang false>[0\1[\$@$@-][\$@$@$@$@\/*=[@\$@+@@]?1+]#%=]p:
<syntaxhighlight lang="false">[0\1[\$@$@-][\$@$@$@$@\/*=[@\$@+@@]?1+]#%=]p:
45p;!." "28p;!. { 0 -1 }</lang>
45p;!." "28p;!. { 0 -1 }</syntaxhighlight>


=={{header|Forth}}==
=={{header|Forth}}==
<lang forth>: perfect? ( n -- ? )
<syntaxhighlight lang="forth">: perfect? ( n -- ? )
1
1
over 2/ 1+ 2 ?do
over 2/ 1+ 2 ?do
over i mod 0= if i + then
over i mod 0= if i + then
loop
loop
= ;</lang>
= ;</syntaxhighlight>


=={{header|Fortran}}==
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
{{works with|Fortran|90 and later}}
<lang fortran>FUNCTION isPerfect(n)
<syntaxhighlight lang="fortran">FUNCTION isPerfect(n)
LOGICAL :: isPerfect
LOGICAL :: isPerfect
INTEGER, INTENT(IN) :: n
INTEGER, INTENT(IN) :: n
Line 1,705: Line 1,705:
END DO
END DO
IF (factorsum == n) isPerfect = .TRUE.
IF (factorsum == n) isPerfect = .TRUE.
END FUNCTION isPerfect</lang>
END FUNCTION isPerfect</syntaxhighlight>


=={{header|FreeBASIC}}==
=={{header|FreeBASIC}}==
{{trans|C (with some modifications)}}
{{trans|C (with some modifications)}}
<lang freebasic>' FB 1.05.0 Win64
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64


Function isPerfect(n As Integer) As Boolean
Function isPerfect(n As Integer) As Boolean
Line 1,732: Line 1,732:
Print
Print
Print "Press any key to quit"
Print "Press any key to quit"
Sleep</lang>
Sleep</syntaxhighlight>


{{out}}
{{out}}
Line 1,741: Line 1,741:


=={{header|Frink}}==
=={{header|Frink}}==
<lang frink>isPerfect = {|n| sum[allFactors[n, true, false]] == n}
<syntaxhighlight lang="frink">isPerfect = {|n| sum[allFactors[n, true, false]] == n}
println[select[1 to 1000, isPerfect]]</lang>
println[select[1 to 1000, isPerfect]]</syntaxhighlight>


{{out}}
{{out}}
Line 1,749: Line 1,749:


=={{header|FunL}}==
=={{header|FunL}}==
<lang funl>def perfect( n ) = sum( d | d <- 1..n if d|n ) == 2n
<syntaxhighlight lang="funl">def perfect( n ) = sum( d | d <- 1..n if d|n ) == 2n


println( (1..500).filter(perfect) )</lang>
println( (1..500).filter(perfect) )</syntaxhighlight>


{{out}}
{{out}}
Line 1,760: Line 1,760:


=={{header|GAP}}==
=={{header|GAP}}==
<lang gap>Filtered([1 .. 10000], n -> Sum(DivisorsInt(n)) = 2*n);
<syntaxhighlight lang="gap">Filtered([1 .. 10000], n -> Sum(DivisorsInt(n)) = 2*n);
# [ 6, 28, 496, 8128 ]</lang>
# [ 6, 28, 496, 8128 ]</syntaxhighlight>


=={{header|Go}}==
=={{header|Go}}==


<lang go>package main
<syntaxhighlight lang="go">package main


import "fmt"
import "fmt"
Line 1,802: Line 1,802:
}
}


</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 1,813: Line 1,813:
=={{header|Groovy}}==
=={{header|Groovy}}==
Solution:
Solution:
<lang groovy>def isPerfect = { n ->
<syntaxhighlight lang="groovy">def isPerfect = { n ->
n > 4 && (n == (2..Math.sqrt(n)).findAll { n % it == 0 }.inject(1) { factorSum, i -> factorSum += i + n/i })
n > 4 && (n == (2..Math.sqrt(n)).findAll { n % it == 0 }.inject(1) { factorSum, i -> factorSum += i + n/i })
}</lang>
}</syntaxhighlight>
Test program:
Test program:
<lang groovy>(0..10000).findAll { isPerfect(it) }.each { println it }</lang>
<syntaxhighlight lang="groovy">(0..10000).findAll { isPerfect(it) }.each { println it }</syntaxhighlight>
{{Out}}
{{Out}}
<pre>6
<pre>6
Line 1,825: Line 1,825:


=={{header|Haskell}}==
=={{header|Haskell}}==
<lang haskell>perfect n =
<syntaxhighlight lang="haskell">perfect n =
n == sum [i | i <- [1..n-1], n `mod` i == 0]</lang>
n == sum [i | i <- [1..n-1], n `mod` i == 0]</syntaxhighlight>


Create a list of known perfects:
Create a list of known perfects:
<lang haskell>perfect =
<syntaxhighlight lang="haskell">perfect =
(\x -> (2 ^ x - 1) * (2 ^ (x - 1))) <$>
(\x -> (2 ^ x - 1) * (2 ^ (x - 1))) <$>
filter (\x -> isPrime x && isPrime (2 ^ x - 1)) maybe_prime
filter (\x -> isPrime x && isPrime (2 ^ x - 1)) maybe_prime
Line 1,847: Line 1,847:
main = do
main = do
mapM_ print $ take 10 perfect
mapM_ print $ take 10 perfect
mapM_ (print . (\x -> (x, isPerfect x))) [6, 27, 28, 29, 496, 8128, 8129]</lang>
mapM_ (print . (\x -> (x, isPerfect x))) [6, 27, 28, 29, 496, 8128, 8129]</syntaxhighlight>




or, restricting the search space to improve performance:
or, restricting the search space to improve performance:
<lang haskell>isPerfect :: Int -> Bool
<syntaxhighlight lang="haskell">isPerfect :: Int -> Bool
isPerfect n =
isPerfect n =
let lows = filter ((0 ==) . rem n) [1 .. floor (sqrt (fromIntegral n))]
let lows = filter ((0 ==) . rem n) [1 .. floor (sqrt (fromIntegral n))]
Line 1,866: Line 1,866:


main :: IO ()
main :: IO ()
main = print $ filter isPerfect [1 .. 10000]</lang>
main = print $ filter isPerfect [1 .. 10000]</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[6,28,496,8128]</pre>
<pre>[6,28,496,8128]</pre>


=={{header|HicEst}}==
=={{header|HicEst}}==
<lang HicEst> DO i = 1, 1E4
<syntaxhighlight lang="hicest"> DO i = 1, 1E4
IF( perfect(i) ) WRITE() i
IF( perfect(i) ) WRITE() i
ENDDO
ENDDO
Line 1,882: Line 1,882:
ENDDO
ENDDO
perfect = sum == n
perfect = sum == n
END</lang>
END</syntaxhighlight>


=={{header|Icon}} and {{header|Unicon}}==
=={{header|Icon}} and {{header|Unicon}}==
<lang Icon>procedure main(arglist)
<syntaxhighlight lang="icon">procedure main(arglist)
limit := \arglist[1] | 100000
limit := \arglist[1] | 100000
write("Perfect numbers from 1 to ",limit,":")
write("Perfect numbers from 1 to ",limit,":")
Line 1,899: Line 1,899:
end
end


link factors</lang>
link factors</syntaxhighlight>


{{libheader|Icon Programming Library}} [http://www.cs.arizona.edu/icon/library/src/procs/factors.icn Uses divisors from factors]
{{libheader|Icon Programming Library}} [http://www.cs.arizona.edu/icon/library/src/procs/factors.icn Uses divisors from factors]
Line 1,912: Line 1,912:


=={{header|J}}==
=={{header|J}}==
<lang j>is_perfect=: +: = >:@#.~/.~&.q:@(6>.<.)</lang>
<syntaxhighlight lang="j">is_perfect=: +: = >:@#.~/.~&.q:@(6>.<.)</syntaxhighlight>


Examples of use, including extensions beyond those assumptions:
Examples of use, including extensions beyond those assumptions:
<lang j> is_perfect 33550336
<syntaxhighlight lang="j"> is_perfect 33550336
1
1
I. is_perfect i. 100000
I. is_perfect i. 100000
Line 1,929: Line 1,929:
0 0 0 0 0 0 0 0 1 0
0 0 0 0 0 0 0 0 1 0
is_perfect 191561942608236107294793378084303638130997321548169216x
is_perfect 191561942608236107294793378084303638130997321548169216x
1</lang>
1</syntaxhighlight>


More efficient version based on [http://jsoftware.com/pipermail/programming/2014-June/037695.html comments] by Henry Rich and Roger Hui (comment train seeded by Jon Hough).
More efficient version based on [http://jsoftware.com/pipermail/programming/2014-June/037695.html comments] by Henry Rich and Roger Hui (comment train seeded by Jon Hough).


=={{header|Java}}==
=={{header|Java}}==
<lang java>public static boolean perf(int n){
<syntaxhighlight lang="java">public static boolean perf(int n){
int sum= 0;
int sum= 0;
for(int i= 1;i < n;i++){
for(int i= 1;i < n;i++){
Line 1,942: Line 1,942:
}
}
return sum == n;
return sum == n;
}</lang>
}</syntaxhighlight>
Or for arbitrary precision:[[Category:Arbitrary precision]]
Or for arbitrary precision:[[Category:Arbitrary precision]]
<lang java>import java.math.BigInteger;
<syntaxhighlight lang="java">import java.math.BigInteger;


public static boolean perf(BigInteger n){
public static boolean perf(BigInteger n){
Line 1,955: Line 1,955:
}
}
return sum.equals(n);
return sum.equals(n);
}</lang>
}</syntaxhighlight>


=={{header|JavaScript}}==
=={{header|JavaScript}}==
Line 1,962: Line 1,962:


{{trans|Java}}
{{trans|Java}}
<lang javascript>function is_perfect(n)
<syntaxhighlight lang="javascript">function is_perfect(n)
{
{
var sum = 1, i, sqrt=Math.floor(Math.sqrt(n));
var sum = 1, i, sqrt=Math.floor(Math.sqrt(n));
Line 1,982: Line 1,982:
if (is_perfect(i))
if (is_perfect(i))
print(i);
print(i);
}</lang>
}</syntaxhighlight>


{{Out}}
{{Out}}
Line 1,996: Line 1,996:
Naive version (brute force)
Naive version (brute force)


<lang JavaScript>(function (nFrom, nTo) {
<syntaxhighlight lang="javascript">(function (nFrom, nTo) {


function perfect(n) {
function perfect(n) {
Line 2,014: Line 2,014:
return range(nFrom, nTo).filter(perfect);
return range(nFrom, nTo).filter(perfect);


})(1, 10000);</lang>
})(1, 10000);</syntaxhighlight>


Output:
Output:


<lang JavaScript>[6, 28, 496, 8128]</lang>
<syntaxhighlight lang="javascript">[6, 28, 496, 8128]</syntaxhighlight>


Much faster (more efficient factorisation)
Much faster (more efficient factorisation)


<lang JavaScript>(function (nFrom, nTo) {
<syntaxhighlight lang="javascript">(function (nFrom, nTo) {


function perfect(n) {
function perfect(n) {
Line 2,044: Line 2,044:
return range(nFrom, nTo).filter(perfect)
return range(nFrom, nTo).filter(perfect)


})(1, 10000);</lang>
})(1, 10000);</syntaxhighlight>


Output:
Output:


<lang JavaScript>[6, 28, 496, 8128]</lang>
<syntaxhighlight lang="javascript">[6, 28, 496, 8128]</syntaxhighlight>


Note that the filter function, though convenient and well optimised, is not strictly necessary.
Note that the filter function, though convenient and well optimised, is not strictly necessary.
Line 2,054: Line 2,054:
(Monadic return/inject for lists is simply lambda x --> [x], inlined here, and fail is [].)
(Monadic return/inject for lists is simply lambda x --> [x], inlined here, and fail is [].)


<lang JavaScript>(function (nFrom, nTo) {
<syntaxhighlight lang="javascript">(function (nFrom, nTo) {


// MONADIC CHAIN (bind) IN LIEU OF FILTER
// MONADIC CHAIN (bind) IN LIEU OF FILTER
Line 2,088: Line 2,088:
}
}


})(1, 10000);</lang>
})(1, 10000);</syntaxhighlight>


Output:
Output:
<lang JavaScript>[6, 28, 496, 8128]</lang>
<syntaxhighlight lang="javascript">[6, 28, 496, 8128]</syntaxhighlight>




====ES6====
====ES6====


<lang JavaScript>(() => {
<syntaxhighlight lang="javascript">(() => {
const main = () =>
const main = () =>
enumFromTo(1, 10000).filter(perfect);
enumFromTo(1, 10000).filter(perfect);
Line 2,120: Line 2,120:
// MAIN ---
// MAIN ---
return main();
return main();
})();</lang>
})();</syntaxhighlight>


{{Out}}
{{Out}}
<lang JavaScript>[6, 28, 496, 8128]</lang>
<syntaxhighlight lang="javascript">[6, 28, 496, 8128]</syntaxhighlight>


=={{header|jq}}==
=={{header|jq}}==
<syntaxhighlight lang="jq">
<lang jq>
def is_perfect:
def is_perfect:
. as $in
. as $in
Line 2,133: Line 2,133:


# Example:
# Example:
range(1;10001) | select( is_perfect )</lang>
range(1;10001) | select( is_perfect )</syntaxhighlight>
{{Out}}
{{Out}}
$ jq -n -f is_perfect.jq
$ jq -n -f is_perfect.jq
Line 2,144: Line 2,144:
{{works with|Julia|0.6}}
{{works with|Julia|0.6}}


<lang julia>isperfect(n::Integer) = n == sum([n % i == 0 ? i : 0 for i = 1:(n - 1)])
<syntaxhighlight lang="julia">isperfect(n::Integer) = n == sum([n % i == 0 ? i : 0 for i = 1:(n - 1)])
perfects(n::Integer) = filter(isperfect, 1:n)
perfects(n::Integer) = filter(isperfect, 1:n)


@show perfects(10000)</lang>
@show perfects(10000)</syntaxhighlight>


{{out}}
{{out}}
Line 2,154: Line 2,154:
=={{header|K}}==
=={{header|K}}==
{{trans|J}}
{{trans|J}}
<lang K> perfect:{(x>2)&x=+/-1_{d:&~x!'!1+_sqrt x;d,_ x%|d}x}
<syntaxhighlight lang="k"> perfect:{(x>2)&x=+/-1_{d:&~x!'!1+_sqrt x;d,_ x%|d}x}
perfect 33550336
perfect 33550336
1
1
Line 2,169: Line 2,169:
(0 0 0 0 0 0 1 0 0 0
(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 0 0
0 0 0 0 0 0 0 0 1 0)</lang>
0 0 0 0 0 0 0 0 1 0)</syntaxhighlight>


=={{header|Kotlin}}==
=={{header|Kotlin}}==
{{trans|C}}
{{trans|C}}
<lang scala>// version 1.0.6
<syntaxhighlight lang="scala">// version 1.0.6


fun isPerfect(n: Int): Boolean = when {
fun isPerfect(n: Int): Boolean = when {
Line 2,196: Line 2,196:
println("The first five perfect numbers are:")
println("The first five perfect numbers are:")
for (i in 2 .. 33550336) if (isPerfect(i)) print("$i ")
for (i in 2 .. 33550336) if (isPerfect(i)) print("$i ")
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 2,208: Line 2,208:


=={{header|Lasso}}==
=={{header|Lasso}}==
<lang lasso>#!/usr/bin/lasso9
<syntaxhighlight lang="lasso">#!/usr/bin/lasso9
define isPerfect(n::integer) => {
define isPerfect(n::integer) => {
Line 2,222: Line 2,222:
with x in generateSeries(1, 10000)
with x in generateSeries(1, 10000)
where isPerfect(#x)
where isPerfect(#x)
select #x</lang>
select #x</syntaxhighlight>
{{Out}}
{{Out}}
<lang lasso>6, 28, 496, 8128</lang>
<syntaxhighlight lang="lasso">6, 28, 496, 8128</syntaxhighlight>


=={{header|Liberty BASIC}}==
=={{header|Liberty BASIC}}==
<lang lb>for n =1 to 10000
<syntaxhighlight lang="lb">for n =1 to 10000
if perfect( n) =1 then print n; " is perfect."
if perfect( n) =1 then print n; " is perfect."
next n
next n
Line 2,245: Line 2,245:
perfect =0
perfect =0
end if
end if
end function</lang>
end function</syntaxhighlight>


=={{header|Lingo}}==
=={{header|Lingo}}==
<lang lingo>on isPercect (n)
<syntaxhighlight lang="lingo">on isPercect (n)
sum = 1
sum = 1
cnt = n/2
cnt = n/2
Line 2,255: Line 2,255:
end repeat
end repeat
return sum=n
return sum=n
end</lang>
end</syntaxhighlight>


=={{header|Logo}}==
=={{header|Logo}}==
<lang logo>to perfect? :n
<syntaxhighlight lang="logo">to perfect? :n
output equal? :n apply "sum filter [equal? 0 modulo :n ?] iseq 1 :n/2
output equal? :n apply "sum filter [equal? 0 modulo :n ?] iseq 1 :n/2
end</lang>
end</syntaxhighlight>


=={{header|Lua}}==
=={{header|Lua}}==
<lang Lua>function isPerfect(x)
<syntaxhighlight lang="lua">function isPerfect(x)
local sum = 0
local sum = 0
for i = 1, x-1 do
for i = 1, x-1 do
Line 2,269: Line 2,269:
end
end
return sum == x
return sum == x
end</lang>
end</syntaxhighlight>


=={{header|M2000 Interpreter}}==
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module PerfectNumbers {
Module PerfectNumbers {
Function Is_Perfect(n as decimal) {
Function Is_Perfect(n as decimal) {
Line 2,344: Line 2,344:
PerfectNumbers
PerfectNumbers
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,363: Line 2,363:


=={{header|M4}}==
=={{header|M4}}==
<lang M4>define(`for',
<syntaxhighlight lang="m4">define(`for',
`ifelse($#,0,``$0'',
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
`ifelse(eval($2<=$3),1,
Line 2,381: Line 2,381:
for(`x',`2',`33550336',
for(`x',`2',`33550336',
`ifelse(isperfect(x),1,`x
`ifelse(isperfect(x),1,`x
')')</lang>
')')</syntaxhighlight>


=={{header|MAD}}==
=={{header|MAD}}==


<lang MAD> NORMAL MODE IS INTEGER
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER
R FUNCTION THAT CHECKS IF NUMBER IS PERFECT
R FUNCTION THAT CHECKS IF NUMBER IS PERFECT
Line 2,403: Line 2,403:
PRINT COMMENT $ $
PRINT COMMENT $ $
END OF PROGRAM
END OF PROGRAM
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 2,414: Line 2,414:


=={{header|Maple}}==
=={{header|Maple}}==
<lang Maple>isperfect := proc(n) return evalb(NumberTheory:-SumOfDivisors(n) = 2*n); end proc:
<syntaxhighlight lang="maple">isperfect := proc(n) return evalb(NumberTheory:-SumOfDivisors(n) = 2*n); end proc:
isperfect(6);
isperfect(6);
true</lang>
true</syntaxhighlight>


=={{header|Mathematica}} / {{header|Wolfram Language}}==
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Custom function:
Custom function:
<lang Mathematica>PerfectQ[i_Integer] := Total[Divisors[i]] == 2 i</lang>
<syntaxhighlight lang="mathematica">PerfectQ[i_Integer] := Total[Divisors[i]] == 2 i</syntaxhighlight>
Examples (testing 496, testing 128, finding all perfect numbers in 1...10000):
Examples (testing 496, testing 128, finding all perfect numbers in 1...10000):
<lang Mathematica>PerfectQ[496]
<syntaxhighlight lang="mathematica">PerfectQ[496]
PerfectQ[128]
PerfectQ[128]
Flatten[PerfectQ/@Range[10000]//Position[#,True]&]</lang>
Flatten[PerfectQ/@Range[10000]//Position[#,True]&]</syntaxhighlight>
gives back:
gives back:
<syntaxhighlight lang="mathematica">True
<lang Mathematica>True
False
False
{6,28,496,8128}</lang>
{6,28,496,8128}</syntaxhighlight>


=={{header|MATLAB}}==
=={{header|MATLAB}}==
Standard algorithm:
Standard algorithm:
<lang MATLAB>function perf = isPerfect(n)
<syntaxhighlight lang="matlab">function perf = isPerfect(n)
total = 0;
total = 0;
for k = 1:n-1
for k = 1:n-1
Line 2,440: Line 2,440:
end
end
perf = total == n;
perf = total == n;
end</lang>
end</syntaxhighlight>
Faster algorithm:
Faster algorithm:
<lang MATLAB>function perf = isPerfect(n)
<syntaxhighlight lang="matlab">function perf = isPerfect(n)
if n < 2
if n < 2
perf = false;
perf = false;
Line 2,461: Line 2,461:
perf = total == n;
perf = total == n;
end
end
end</lang>
end</syntaxhighlight>


=={{header|Maxima}}==
=={{header|Maxima}}==
<lang maxima>".."(a, b) := makelist(i, i, a, b)$
<syntaxhighlight lang="maxima">".."(a, b) := makelist(i, i, a, b)$
infix("..")$
infix("..")$


Line 2,470: Line 2,470:


sublist(1 .. 10000, perfectp);
sublist(1 .. 10000, perfectp);
/* [6, 28, 496, 8128] */</lang>
/* [6, 28, 496, 8128] */</syntaxhighlight>


=={{header|MAXScript}}==
=={{header|MAXScript}}==
<lang maxscript>fn isPerfect n =
<syntaxhighlight lang="maxscript">fn isPerfect n =
(
(
local sum = 0
local sum = 0
Line 2,484: Line 2,484:
)
)
sum == n
sum == n
)</lang>
)</syntaxhighlight>


=={{header|Microsoft Small Basic}}==
=={{header|Microsoft Small Basic}}==
{{trans|BBC BASIC}}
{{trans|BBC BASIC}}
<lang microsoftsmallbasic>
<syntaxhighlight lang="microsoftsmallbasic">
For n = 2 To 10000 Step 2
For n = 2 To 10000 Step 2
VerifyIfPerfect()
VerifyIfPerfect()
Line 2,518: Line 2,518:
EndIf
EndIf
EndSub
EndSub
</syntaxhighlight>
</lang>


=={{header|Modula-2}}==
=={{header|Modula-2}}==
{{trans|BBC BASIC}}
{{trans|BBC BASIC}}
{{works with|ADW Modula-2|any (Compile with the linker option ''Console Application'').}}
{{works with|ADW Modula-2|any (Compile with the linker option ''Console Application'').}}
<lang modula2>
<syntaxhighlight lang="modula2">
MODULE PerfectNumbers;
MODULE PerfectNumbers;


Line 2,567: Line 2,567:
END;
END;
END PerfectNumbers.
END PerfectNumbers.
</syntaxhighlight>
</lang>


=={{header|Nanoquery}}==
=={{header|Nanoquery}}==
{{trans|Python}}
{{trans|Python}}
<lang Nanoquery>def perf(n)
<syntaxhighlight lang="nanoquery">def perf(n)
sum = 0
sum = 0
for i in range(1, n - 1)
for i in range(1, n - 1)
Line 2,579: Line 2,579:
end
end
return sum = n
return sum = n
end</lang>
end</syntaxhighlight>


=={{header|Nim}}==
=={{header|Nim}}==
<lang nim>import math
<syntaxhighlight lang="nim">import math


proc isPerfect(n: int): bool =
proc isPerfect(n: int): bool =
Line 2,595: Line 2,595:
for n in 2..10_000:
for n in 2..10_000:
if n.isPerfect:
if n.isPerfect:
echo n</lang>
echo n</syntaxhighlight>


{{out}}
{{out}}
Line 2,604: Line 2,604:


=={{header|Objeck}}==
=={{header|Objeck}}==
<lang objeck>bundle Default {
<syntaxhighlight lang="objeck">bundle Default {
class Test {
class Test {
function : Main(args : String[]) ~ Nil {
function : Main(args : String[]) ~ Nil {
Line 2,626: Line 2,626:
}
}
}
}
}</lang>
}</syntaxhighlight>


=={{header|OCaml}}==
=={{header|OCaml}}==
<lang ocaml>let perf n =
<syntaxhighlight lang="ocaml">let perf n =
let sum = ref 0 in
let sum = ref 0 in
for i = 1 to n-1 do
for i = 1 to n-1 do
Line 2,635: Line 2,635:
sum := !sum + i
sum := !sum + i
done;
done;
!sum = n</lang>
!sum = n</syntaxhighlight>
Functional style:
Functional style:
<lang ocaml>(* range operator *)
<syntaxhighlight lang="ocaml">(* range operator *)
let rec (--) a b =
let rec (--) a b =
if a > b then
if a > b then
Line 2,644: Line 2,644:
a :: (a+1) -- b
a :: (a+1) -- b


let perf n = n = List.fold_left (+) 0 (List.filter (fun i -> n mod i = 0) (1 -- (n-1)))</lang>
let perf n = n = List.fold_left (+) 0 (List.filter (fun i -> n mod i = 0) (1 -- (n-1)))</syntaxhighlight>


=={{header|Oforth}}==
=={{header|Oforth}}==


<lang Oforth>: isPerfect(n) | i | 0 n 2 / loop: i [ n i mod ifZero: [ i + ] ] n == ; </lang>
<syntaxhighlight lang="oforth">: isPerfect(n) | i | 0 n 2 / loop: i [ n i mod ifZero: [ i + ] ] n == ; </syntaxhighlight>


{{out}}
{{out}}
Line 2,657: Line 2,657:


=={{header|ooRexx}}==
=={{header|ooRexx}}==
<lang ooRexx>-- first perfect number over 10000 is 33550336...let's not be crazy
<syntaxhighlight lang="oorexx">-- first perfect number over 10000 is 33550336...let's not be crazy
loop i = 1 to 10000
loop i = 1 to 10000
if perfectNumber(i) then say i "is a perfect number"
if perfectNumber(i) then say i "is a perfect number"
Line 2,673: Line 2,673:
end
end


return sum = n</lang>
return sum = n</syntaxhighlight>
{{out}}
{{out}}
<pre>6 is a perfect number
<pre>6 is a perfect number
Line 2,681: Line 2,681:


=={{header|Oz}}==
=={{header|Oz}}==
<lang oz>declare
<syntaxhighlight lang="oz">declare
fun {IsPerfect N}
fun {IsPerfect N}
fun {IsNFactor I} N mod I == 0 end
fun {IsNFactor I} N mod I == 0 end
Line 2,692: Line 2,692:
in
in
{Show {Filter {List.number 1 10000 1} IsPerfect}}
{Show {Filter {List.number 1 10000 1} IsPerfect}}
{Show {IsPerfect 33550336}}</lang>
{Show {IsPerfect 33550336}}</syntaxhighlight>


=={{header|PARI/GP}}==
=={{header|PARI/GP}}==
Uses built-in method. Faster tests would use the LL test for evens and myriad results on OPNs otherwise.
Uses built-in method. Faster tests would use the LL test for evens and myriad results on OPNs otherwise.
<lang parigp>isPerfect(n)=sigma(n,-1)==2</lang>
<syntaxhighlight lang="parigp">isPerfect(n)=sigma(n,-1)==2</syntaxhighlight>
Show perfect numbers
Show perfect numbers
<lang parigp>forprime(p=2, 2281,
<syntaxhighlight lang="parigp">forprime(p=2, 2281,
if(isprime(2^p-1),
if(isprime(2^p-1),
print(p"\t",(2^p-1)*2^(p-1))))</lang>
print(p"\t",(2^p-1)*2^(p-1))))</syntaxhighlight>
Faster with Lucas-Lehmer test
Faster with Lucas-Lehmer test
<lang parigp>p=2;n=3;n1=2;
<syntaxhighlight lang="parigp">p=2;n=3;n1=2;
while(p<2281,
while(p<2281,
if(isprime(p),
if(isprime(p),
Line 2,710: Line 2,710:
if(s==0 || p==2,
if(s==0 || p==2,
print("(2^"p"-1)2^("p"-1)=\t"n1*n"\n")));
print("(2^"p"-1)2^("p"-1)=\t"n1*n"\n")));
p++; n1=n+1; n=2*n+1)</lang>
p++; n1=n+1; n=2*n+1)</syntaxhighlight>
{{Out}}
{{Out}}
<pre>(2^2-1)2^(2-1)= 6
<pre>(2^2-1)2^(2-1)= 6
Line 2,724: Line 2,724:


=={{header|Pascal}}==
=={{header|Pascal}}==
<lang pascal>program PerfectNumbers;
<syntaxhighlight lang="pascal">program PerfectNumbers;


function isPerfect(number: longint): boolean;
function isPerfect(number: longint): boolean;
Line 2,746: Line 2,746:
if isPerfect(candidate) then
if isPerfect(candidate) then
writeln (candidate, ' is a perfect number.');
writeln (candidate, ' is a perfect number.');
end.</lang>
end.</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 2,759: Line 2,759:
=={{header|Perl}}==
=={{header|Perl}}==
=== Functions ===
=== Functions ===
<lang perl>sub perf {
<syntaxhighlight lang="perl">sub perf {
my $n = shift;
my $n = shift;
my $sum = 0;
my $sum = 0;
Line 2,768: Line 2,768:
}
}
return $sum == $n;
return $sum == $n;
}</lang>
}</syntaxhighlight>
Functional style:
Functional style:
<lang perl>use List::Util qw(sum);
<syntaxhighlight lang="perl">use List::Util qw(sum);


sub perf {
sub perf {
my $n = shift;
my $n = shift;
$n == sum(0, grep {$n % $_ == 0} 1..$n-1);
$n == sum(0, grep {$n % $_ == 0} 1..$n-1);
}</lang>
}</syntaxhighlight>
=== Modules ===
=== Modules ===
The functions above are terribly slow. As usual, this is easier and faster with modules. Both ntheory and Math::Pari have useful functions for this.
The functions above are terribly slow. As usual, this is easier and faster with modules. Both ntheory and Math::Pari have useful functions for this.
{{libheader|ntheory}}
{{libheader|ntheory}}
A simple predicate:
A simple predicate:
<lang perl>use ntheory qw/divisor_sum/;
<syntaxhighlight lang="perl">use ntheory qw/divisor_sum/;
sub is_perfect { my $n = shift; divisor_sum($n) == 2*$n; }</lang>
sub is_perfect { my $n = shift; divisor_sum($n) == 2*$n; }</syntaxhighlight>
Use this naive method to show the first 5. Takes about 15 seconds:
Use this naive method to show the first 5. Takes about 15 seconds:
<lang perl>use ntheory qw/divisor_sum/;
<syntaxhighlight lang="perl">use ntheory qw/divisor_sum/;
for (1..33550336) {
for (1..33550336) {
print "$_\n" if divisor_sum($_) == 2*$_;
print "$_\n" if divisor_sum($_) == 2*$_;
}</lang>
}</syntaxhighlight>
Or we can be clever and look for 2^(p-1) * (2^p-1) where 2^p -1 is prime. The first 20 takes about a second.
Or we can be clever and look for 2^(p-1) * (2^p-1) where 2^p -1 is prime. The first 20 takes about a second.
<lang perl>use ntheory qw/forprimes is_prime/;
<syntaxhighlight lang="perl">use ntheory qw/forprimes is_prime/;
use bigint;
use bigint;
forprimes {
forprimes {
my $n = 2**$_ - 1;
my $n = 2**$_ - 1;
print "$_\t", $n * 2**($_-1),"\n" if is_prime($n);
print "$_\t", $n * 2**($_-1),"\n" if is_prime($n);
} 2, 4500;</lang>
} 2, 4500;</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 2,810: Line 2,810:


We can speed this up even more using a faster program for printing the large results, as well as a faster primality solution. The first 38 in about 1 second with most of the time printing the large results. Caveat: this goes well past the current bound for odd perfect numbers and does not check for them.
We can speed this up even more using a faster program for printing the large results, as well as a faster primality solution. The first 38 in about 1 second with most of the time printing the large results. Caveat: this goes well past the current bound for odd perfect numbers and does not check for them.
<lang perl>use ntheory qw/forprimes is_mersenne_prime/;
<syntaxhighlight lang="perl">use ntheory qw/forprimes is_mersenne_prime/;
use Math::GMP qw/:constant/;
use Math::GMP qw/:constant/;
forprimes {
forprimes {
print "$_\t", (2**$_-1)*2**($_-1),"\n" if is_mersenne_prime($_);
print "$_\t", (2**$_-1)*2**($_-1),"\n" if is_mersenne_prime($_);
} 7_000_000;</lang>
} 7_000_000;</syntaxhighlight>


In addition to generating even perfect numbers, we can also have a fast function which returns true when a given even number is perfect:
In addition to generating even perfect numbers, we can also have a fast function which returns true when a given even number is perfect:
<lang perl>use ntheory qw(is_mersenne_prime valuation);
<syntaxhighlight lang="perl">use ntheory qw(is_mersenne_prime valuation);


sub is_even_perfect {
sub is_even_perfect {
Line 2,826: Line 2,826:
($m >> $v) == 1 || return;
($m >> $v) == 1 || return;
is_mersenne_prime($v + 1);
is_mersenne_prime($v + 1);
}</lang>
}</syntaxhighlight>


=={{header|Phix}}==
=={{header|Phix}}==
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">is_perfect</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">is_perfect</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">))=</span><span style="color: #000000;">n</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">))=</span><span style="color: #000000;">n</span>
Line 2,837: Line 2,837:
<span style="color: #008080;">if</span> <span style="color: #000000;">is_perfect</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">i</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">is_perfect</span><span style="color: #0000FF;">(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?</span><span style="color: #000000;">i</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,847: Line 2,847:
=== gmp version ===
=== gmp version ===
{{libheader|Phix/mpfr}}
{{libheader|Phix/mpfr}}
<!--<lang Phix>(phixonline)-->
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Perfect_numbers.exw (includes native version above)</span>
<span style="color: #000080;font-style:italic;">-- demo\rosetta\Perfect_numbers.exw (includes native version above)</span>
Line 2,862: Line 2,862:
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_free</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">n</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">mpz_free</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<!--</lang>-->
<!--</syntaxhighlight>-->
{{out}}
{{out}}
<pre>
<pre>
Line 2,881: Line 2,881:
=={{header|PHP}}==
=={{header|PHP}}==
{{trans|C++}}
{{trans|C++}}
<lang php>function is_perfect($number)
<syntaxhighlight lang="php">function is_perfect($number)
{
{
$sum = 0;
$sum = 0;
Line 2,897: Line 2,897:
if(is_perfect($num))
if(is_perfect($num))
echo $num . PHP_EOL;
echo $num . PHP_EOL;
}</lang>
}</syntaxhighlight>


=={{header|Picat}}==
=={{header|Picat}}==
===Simple divisors/1 function===
===Simple divisors/1 function===
First is the slow <code>perfect1/1</code> that use the simple divisors/1 function:
First is the slow <code>perfect1/1</code> that use the simple divisors/1 function:
<lang Picat>go =>
<syntaxhighlight lang="picat">go =>
println(perfect1=[I : I in 1..10_000, perfect1(I)]),
println(perfect1=[I : I in 1..10_000, perfect1(I)]),
nl.
nl.
perfect1(N) => sum(divisors(N)) == N.
perfect1(N) => sum(divisors(N)) == N.
divisors(N) = [J: J in 1..1+N div 2, N mod J == 0].</lang>
divisors(N) = [J: J in 1..1+N div 2, N mod J == 0].</syntaxhighlight>


{{out}}
{{out}}
Line 2,914: Line 2,914:
===Using formula for perfect number candidates===
===Using formula for perfect number candidates===
The formula for perfect number candidates is: 2^(p-1)*(2^p-1) for prime p. This is used to find some more perfect numbers in reasonable time. <code>perfect2/1</code> is a faster version of checking if a number is perfect.
The formula for perfect number candidates is: 2^(p-1)*(2^p-1) for prime p. This is used to find some more perfect numbers in reasonable time. <code>perfect2/1</code> is a faster version of checking if a number is perfect.
<lang Picat>go2 =>
<syntaxhighlight lang="picat">go2 =>
println("Using the formula: 2^(p-1)*(2^p-1) for prime p"),
println("Using the formula: 2^(p-1)*(2^p-1) for prime p"),
foreach(P in primes(32))
foreach(P in primes(32))
Line 2,953: Line 2,953:
% I is not a divisor of N.
% I is not a divisor of N.
sum_divisors(I,N,Sum0,Sum) =>
sum_divisors(I,N,Sum0,Sum) =>
sum_divisors(I+1,N,Sum0,Sum).</lang>
sum_divisors(I+1,N,Sum0,Sum).</syntaxhighlight>


{{out}}
{{out}}
Line 2,971: Line 2,971:


The perfect numbers are printed only if they has < 80 digits, otherwise the number of digits are shown. The program stops when reaching a number with more than 100 000 digits. (Note: The major time running this program is getting the number of digits.)
The perfect numbers are printed only if they has < 80 digits, otherwise the number of digits are shown. The program stops when reaching a number with more than 100 000 digits. (Note: The major time running this program is getting the number of digits.)
<lang Picat>go3 =>
<syntaxhighlight lang="picat">go3 =>
ValidP = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607,
ValidP = [2, 3, 5, 7, 13, 17, 19, 31, 61, 89, 107, 127, 521, 607,
1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213,
1279, 2203, 2281, 3217, 4253, 4423, 9689, 9941, 11213,
Line 2,992: Line 2,992:
end
end
end,
end,
nl.</lang>
nl.</syntaxhighlight>


{{out}}
{{out}}
Line 3,028: Line 3,028:


=={{header|PicoLisp}}==
=={{header|PicoLisp}}==
<lang PicoLisp>(de perfect (N)
<syntaxhighlight lang="picolisp">(de perfect (N)
(let C 0
(let C 0
(for I (/ N 2)
(for I (/ N 2)
(and (=0 (% N I)) (inc 'C I)) )
(and (=0 (% N I)) (inc 'C I)) )
(= C N) ) )</lang>
(= C N) ) )</syntaxhighlight>


<lang PicoLisp>(de faster (N)
<syntaxhighlight lang="picolisp">(de faster (N)
(let (C 1 Stop (sqrt N))
(let (C 1 Stop (sqrt N))
(for (I 2 (<= I Stop) (inc I))
(for (I 2 (<= I Stop) (inc I))
Line 3,040: Line 3,040:
(=0 (% N I))
(=0 (% N I))
(inc 'C (+ (/ N I) I)) ) )
(inc 'C (+ (/ N I) I)) ) )
(= C N) ) )</lang>
(= C N) ) )</syntaxhighlight>


=={{header|PL/I}}==
=={{header|PL/I}}==
<lang PL/I>perfect: procedure (n) returns (bit(1));
<syntaxhighlight lang="pl/i">perfect: procedure (n) returns (bit(1));
declare n fixed;
declare n fixed;
declare sum fixed;
declare sum fixed;
Line 3,053: Line 3,053:
end;
end;
return (sum=n);
return (sum=n);
end perfect;</lang>
end perfect;</syntaxhighlight>


==={{header|PL/I-80}}===
==={{header|PL/I-80}}===
<lang PL/I>perfect_search: procedure options (main);
<syntaxhighlight lang="pl/i">perfect_search: procedure options (main);


%replace
%replace
Line 3,097: Line 3,097:
end isperfect;
end isperfect;


end perfect_search;</lang>
end perfect_search;</syntaxhighlight>


{{out}}
{{out}}
Line 3,111: Line 3,111:
=={{header|PL/M}}==
=={{header|PL/M}}==
{{works with|8080 PL/M Compiler}} ... under CP/M (or an emulator)
{{works with|8080 PL/M Compiler}} ... under CP/M (or an emulator)
<lang pli>100H: /* FIND SOME PERFECT NUMBERS: NUMBERS EQUAL TO THE SUM OF THEIR PROPER */
<syntaxhighlight lang="pli">100H: /* FIND SOME PERFECT NUMBERS: NUMBERS EQUAL TO THE SUM OF THEIR PROPER */
/* DIVISORS */
/* DIVISORS */
/* CP/M SYSTEM CALL AND I/O ROUTINES */
/* CP/M SYSTEM CALL AND I/O ROUTINES */
Line 3,161: Line 3,161:
END;
END;
END;
END;
EOF</lang>
EOF</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,170: Line 3,170:
{{Trans|Action!}}
{{Trans|Action!}}
{{works with|8080 PL/M Compiler}} ... under CP/M (or an emulator)
{{works with|8080 PL/M Compiler}} ... under CP/M (or an emulator)
<lang pli>100H: /* FIND SOME PERFECT NUMBERS: NUMBERS EQUAL TO THE SUM OF THEIR PROPER */
<syntaxhighlight lang="pli">100H: /* FIND SOME PERFECT NUMBERS: NUMBERS EQUAL TO THE SUM OF THEIR PROPER */
/* DIVISORS */
/* DIVISORS */
/* CP/M SYSTEM CALL AND I/O ROUTINES */
/* CP/M SYSTEM CALL AND I/O ROUTINES */
Line 3,213: Line 3,213:
END;
END;
END;
END;
EOF</lang>
EOF</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,223: Line 3,223:


=={{header|PowerShell}}==
=={{header|PowerShell}}==
<lang powershell>Function IsPerfect($n)
<syntaxhighlight lang="powershell">Function IsPerfect($n)
{
{
$sum=0
$sum=0
Line 3,236: Line 3,236:
}
}


Returns "True" if the given number is perfect and "False" if it's not.</lang>
Returns "True" if the given number is perfect and "False" if it's not.</syntaxhighlight>


=={{header|Prolog}}==
=={{header|Prolog}}==
===Classic approach===
===Classic approach===
Works with SWI-Prolog
Works with SWI-Prolog
<lang Prolog>tt_divisors(X, N, TT) :-
<syntaxhighlight lang="prolog">tt_divisors(X, N, TT) :-
Q is X / N,
Q is X / N,
( 0 is X mod N -> (Q = N -> TT1 is N + TT;
( 0 is X mod N -> (Q = N -> TT1 is N + TT;
Line 3,254: Line 3,254:
perfect_numbers(N, L) :-
perfect_numbers(N, L) :-
numlist(2, N, LN),
numlist(2, N, LN),
include(perfect, LN, L).</lang>
include(perfect, LN, L).</syntaxhighlight>


===Faster method===
===Faster method===
Since a perfect number is of the form 2^(n-1) * (2^n - 1), we can eliminate a lot of candidates by merely factoring out the 2s and seeing if the odd portion is (2^(n+1)) - 1.
Since a perfect number is of the form 2^(n-1) * (2^n - 1), we can eliminate a lot of candidates by merely factoring out the 2s and seeing if the odd portion is (2^(n+1)) - 1.
<syntaxhighlight lang="prolog">
<lang Prolog>
perfect(N) :-
perfect(N) :-
factor_2s(N, Chk, Exp),
factor_2s(N, Chk, Exp),
Line 3,285: Line 3,285:
N mod D =\= 0,
N mod D =\= 0,
D2 is D + A, prime(N, D2, As).
D2 is D + A, prime(N, D2, As).
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,298: Line 3,298:
===Functional approach===
===Functional approach===
Works with SWI-Prolog and module lambda, written by <b>Ulrich Neumerkel</b> found there http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl
Works with SWI-Prolog and module lambda, written by <b>Ulrich Neumerkel</b> found there http://www.complang.tuwien.ac.at/ulrich/Prolog-inedit/lambda.pl
<lang Prolog>:- use_module(library(lambda)).
<syntaxhighlight lang="prolog">:- use_module(library(lambda)).


is_divisor(V, N) :-
is_divisor(V, N) :-
Line 3,334: Line 3,334:
%% f_compose_1(Pred1, Pred2, Pred1(Pred2)).
%% f_compose_1(Pred1, Pred2, Pred1(Pred2)).
%
%
f_compose_1(F,G, \X^Z^(call(G,X,Y), call(F,Y,Z))).</lang>
f_compose_1(F,G, \X^Z^(call(G,X,Y), call(F,Y,Z))).</syntaxhighlight>


=={{header|PureBasic}}==
=={{header|PureBasic}}==
<lang PureBasic>Procedure is_Perfect_number(n)
<syntaxhighlight lang="purebasic">Procedure is_Perfect_number(n)
Protected summa, i=1, result=#False
Protected summa, i=1, result=#False
Repeat
Repeat
Line 3,349: Line 3,349:
EndIf
EndIf
ProcedureReturn result
ProcedureReturn result
EndProcedure</lang>
EndProcedure</syntaxhighlight>


=={{header|Python}}==
=={{header|Python}}==
Line 3,378: Line 3,378:


===Python: Procedural===
===Python: Procedural===
<lang python>def perf1(n):
<syntaxhighlight lang="python">def perf1(n):
sum = 0
sum = 0
for i in range(1, n):
for i in range(1, n):
if n % i == 0:
if n % i == 0:
sum += i
sum += i
return sum == n</lang>
return sum == n</syntaxhighlight>


===Python: Optimised Procedural===
===Python: Optimised Procedural===
<lang python>from itertools import chain, cycle, accumulate
<syntaxhighlight lang="python">from itertools import chain, cycle, accumulate


def factor2(n):
def factor2(n):
Line 3,407: Line 3,407:
def perf4(n):
def perf4(n):
"Using most efficient prime factoring routine from: http://rosettacode.org/wiki/Factors_of_an_integer#Python"
"Using most efficient prime factoring routine from: http://rosettacode.org/wiki/Factors_of_an_integer#Python"
return 2 * n == sum(factor2(n))</lang>
return 2 * n == sum(factor2(n))</syntaxhighlight>


===Python: Functional===
===Python: Functional===
<lang python>def perf2(n):
<syntaxhighlight lang="python">def perf2(n):
return n == sum(i for i in range(1, n) if n % i == 0)
return n == sum(i for i in range(1, n) if n % i == 0)


print (
print (
list(filter(perf2, range(1, 10001)))
list(filter(perf2, range(1, 10001)))
)</lang>
)</syntaxhighlight>






<lang python>'''Perfect numbers'''
<syntaxhighlight lang="python">'''Perfect numbers'''


from math import sqrt
from math import sqrt
Line 3,453: Line 3,453:


if __name__ == '__main__':
if __name__ == '__main__':
main()</lang>
main()</syntaxhighlight>
{{Out}}
{{Out}}
<pre>[6, 28, 496, 8128]</pre>
<pre>[6, 28, 496, 8128]</pre>
Line 3,461: Line 3,461:
<code>factors</code> is defined at [http://rosettacode.org/wiki/Factors_of_an_integer#Quackery Factors of an integer].
<code>factors</code> is defined at [http://rosettacode.org/wiki/Factors_of_an_integer#Quackery Factors of an integer].


<lang Quackery> [ 0 swap witheach + ] is sum ( [ --> n )
<syntaxhighlight lang="quackery"> [ 0 swap witheach + ] is sum ( [ --> n )


[ factors -1 pluck dip sum = ] is perfect ( n --> n )
[ factors -1 pluck dip sum = ] is perfect ( n --> n )
Line 3,468: Line 3,468:
10000 times
10000 times
[ i^ 1+ perfect if [ i^ 1+ echo cr ] ]
[ i^ 1+ perfect if [ i^ 1+ echo cr ] ]
</syntaxhighlight>
</lang>


{{out}}
{{out}}
Line 3,480: Line 3,480:


=={{header|R}}==
=={{header|R}}==
<lang R>is.perf <- function(n){
<syntaxhighlight lang="r">is.perf <- function(n){
if (n==0|n==1) return(FALSE)
if (n==0|n==1) return(FALSE)
s <- seq (1,n-1)
s <- seq (1,n-1)
Line 3,490: Line 3,490:
# Usage - Warning High Memory Usage
# Usage - Warning High Memory Usage
is.perf(28)
is.perf(28)
sapply(c(6,28,496,8128,33550336),is.perf)</lang>
sapply(c(6,28,496,8128,33550336),is.perf)</syntaxhighlight>


=={{header|Racket}}==
=={{header|Racket}}==
<lang racket>#lang racket
<syntaxhighlight lang="racket">#lang racket
(require math)
(require math)


Line 3,503: Line 3,503:
; filtering to only even numbers for better performance
; filtering to only even numbers for better performance
(filter perfect? (filter even? (range 1e5)))
(filter perfect? (filter even? (range 1e5)))
;-> '(0 6 28 496 8128)</lang>
;-> '(0 6 28 496 8128)</syntaxhighlight>


=={{header|Raku}}==
=={{header|Raku}}==
(formerly Perl 6)
(formerly Perl 6)
Naive (very slow) version
Naive (very slow) version
<lang perl6>sub is-perf($n) { $n == [+] grep $n %% *, 1 .. $n div 2 }
<syntaxhighlight lang="raku" line>sub is-perf($n) { $n == [+] grep $n %% *, 1 .. $n div 2 }


# used as
# used as
put ((1..Inf).hyper.grep: {.&is-perf})[^4];</lang>
put ((1..Inf).hyper.grep: {.&is-perf})[^4];</syntaxhighlight>
{{out}}
{{out}}
<pre>6 28 496 8128</pre>
<pre>6 28 496 8128</pre>
Much, much faster version:
Much, much faster version:
<lang perl6>my @primes = lazy (2,3,*+2 … Inf).grep: { .is-prime };
<syntaxhighlight lang="raku" line>my @primes = lazy (2,3,*+2 … Inf).grep: { .is-prime };
my @perfects = lazy gather for @primes {
my @perfects = lazy gather for @primes {
my $n = 2**$_ - 1;
my $n = 2**$_ - 1;
Line 3,521: Line 3,521:
}
}


.put for @perfects[^12];</lang>
.put for @perfects[^12];</syntaxhighlight>


{{out}}
{{out}}
Line 3,538: Line 3,538:


=={{header|REBOL}}==
=={{header|REBOL}}==
<lang rebol>perfect?: func [n [integer!] /local sum] [
<syntaxhighlight lang="rebol">perfect?: func [n [integer!] /local sum] [
sum: 0
sum: 0
repeat i (n - 1) [
repeat i (n - 1) [
Line 3,546: Line 3,546:
]
]
sum = n
sum = n
]</lang>
]</syntaxhighlight>


=={{header|REXX}}==
=={{header|REXX}}==
===Classic REXX version of ooRexx===
===Classic REXX version of ooRexx===
This version is a '''Classic Rexx''' version of the '''ooRexx''' program as of 14-Sep-2013.
This version is a '''Classic Rexx''' version of the '''ooRexx''' program as of 14-Sep-2013.
<lang rexx>/*REXX version of the ooRexx program (the code was modified to run with Classic REXX).*/
<syntaxhighlight lang="rexx">/*REXX version of the ooRexx program (the code was modified to run with Classic REXX).*/
do i=1 to 10000 /*statement changed: LOOP ──► DO*/
do i=1 to 10000 /*statement changed: LOOP ──► DO*/
if perfectNumber(i) then say i "is a perfect number"
if perfectNumber(i) then say i "is a perfect number"
Line 3,562: Line 3,562:
if n//i==0 then sum=sum+i /*statement changed: sum += i */
if n//i==0 then sum=sum+i /*statement changed: sum += i */
end
end
return sum=n</lang>
return sum=n</syntaxhighlight>
'''output''' &nbsp; when using the default of 10000:
'''output''' &nbsp; when using the default of 10000:
<pre>
<pre>
Line 3,574: Line 3,574:
This version is a '''Classic REXX''' version of the '''PL/I''' program as of 14-Sep-2013, &nbsp; a REXX &nbsp; '''say''' &nbsp; statement
This version is a '''Classic REXX''' version of the '''PL/I''' program as of 14-Sep-2013, &nbsp; a REXX &nbsp; '''say''' &nbsp; statement
<br>was added to display the perfect numbers. &nbsp; Also, an epilog was written for the re-worked function.
<br>was added to display the perfect numbers. &nbsp; Also, an epilog was written for the re-worked function.
<lang rexx>/*REXX version of the PL/I program (code was modified to run with Classic REXX). */
<syntaxhighlight lang="rexx">/*REXX version of the PL/I program (code was modified to run with Classic REXX). */
parse arg low high . /*obtain the specified number(s).*/
parse arg low high . /*obtain the specified number(s).*/
if high=='' & low=='' then high=34000000 /*if no arguments, use a range. */
if high=='' & low=='' then high=34000000 /*if no arguments, use a range. */
Line 3,590: Line 3,590:
if n//i==0 then sum=sum+i /*I is a factor of N, so add it.*/
if n//i==0 then sum=sum+i /*I is a factor of N, so add it.*/
end /*i*/
end /*i*/
return sum=n /*if the sum matches N, perfect! */</lang>
return sum=n /*if the sum matches N, perfect! */</syntaxhighlight>
'''output''' &nbsp; when using the input defaults of: &nbsp; <tt> 1 &nbsp; 10000 </tt>
'''output''' &nbsp; when using the input defaults of: &nbsp; <tt> 1 &nbsp; 10000 </tt>


Line 3,600: Line 3,600:
:::* &nbsp; testing bypasses the test of the first and last factors
:::* &nbsp; testing bypasses the test of the first and last factors
:::* &nbsp; the &nbsp; ''corresponding factor'' &nbsp; is also used when a factor is found
:::* &nbsp; the &nbsp; ''corresponding factor'' &nbsp; is also used when a factor is found
<lang rexx>/*REXX program tests if a number (or a range of numbers) is/are perfect. */
<syntaxhighlight lang="rexx">/*REXX program tests if a number (or a range of numbers) is/are perfect. */
parse arg low high . /*obtain optional arguments from the CL*/
parse arg low high . /*obtain optional arguments from the CL*/
if high=='' & low=="" then high=34000000 /*if no arguments, then use a range. */
if high=='' & low=="" then high=34000000 /*if no arguments, then use a range. */
Line 3,620: Line 3,620:
s = s + j + x%j /* ··· add it and the other factor. */
s = s + j + x%j /* ··· add it and the other factor. */
end /*j*/ /*(above) is marginally faster. */
end /*j*/ /*(above) is marginally faster. */
return s==x /*if the sum matches X, it's perfect! */</lang>
return s==x /*if the sum matches X, it's perfect! */</syntaxhighlight>
'''output''' &nbsp; when using the default inputs:
'''output''' &nbsp; when using the default inputs:
<pre>
<pre>
Line 3,635: Line 3,635:
===optimized using digital root===
===optimized using digital root===
This REXX version makes use of the fact that all &nbsp; ''known'' &nbsp; perfect numbers > 6 have a &nbsp; ''digital root'' &nbsp; of &nbsp; '''1'''.
This REXX version makes use of the fact that all &nbsp; ''known'' &nbsp; perfect numbers > 6 have a &nbsp; ''digital root'' &nbsp; of &nbsp; '''1'''.
<lang rexx>/*REXX program tests if a number (or a range of numbers) is/are perfect. */
<syntaxhighlight lang="rexx">/*REXX program tests if a number (or a range of numbers) is/are perfect. */
parse arg low high . /*obtain the specified number(s). */
parse arg low high . /*obtain the specified number(s). */
if high=='' & low=="" then high=34000000 /*if no arguments, then use a range. */
if high=='' & low=="" then high=34000000 /*if no arguments, then use a range. */
Line 3,662: Line 3,662:
s = s + j + x%j /*··· add it and the other factor. */
s = s + j + x%j /*··· add it and the other factor. */
end /*j*/ /*(above) is marginally faster. */
end /*j*/ /*(above) is marginally faster. */
return s==x /*if the sum matches X, it's perfect! */</lang>
return s==x /*if the sum matches X, it's perfect! */</syntaxhighlight>
'''output''' &nbsp; is the same as the traditional version &nbsp; and is about &nbsp; '''5.3''' &nbsp; times faster &nbsp; (testing '''34,000,000''' numbers).
'''output''' &nbsp; is the same as the traditional version &nbsp; and is about &nbsp; '''5.3''' &nbsp; times faster &nbsp; (testing '''34,000,000''' numbers).


===optimized using only even numbers===
===optimized using only even numbers===
This REXX version uses the fact that all &nbsp; ''known'' &nbsp; perfect numbers are &nbsp; ''even''.
This REXX version uses the fact that all &nbsp; ''known'' &nbsp; perfect numbers are &nbsp; ''even''.
<lang rexx>/*REXX program tests if a number (or a range of numbers) is/are perfect. */
<syntaxhighlight lang="rexx">/*REXX program tests if a number (or a range of numbers) is/are perfect. */
parse arg low high . /*obtain optional arguments from the CL*/
parse arg low high . /*obtain optional arguments from the CL*/
if high=='' & low=="" then high=34000000 /*if no arguments, then use a range. */
if high=='' & low=="" then high=34000000 /*if no arguments, then use a range. */
Line 3,695: Line 3,695:
s = s + j + x%j /* ··· add it and the other factor. */
s = s + j + x%j /* ··· add it and the other factor. */
end /*j*/ /*(above) is marginally faster. */
end /*j*/ /*(above) is marginally faster. */
return s==x /*if sum matches X, then it's perfect!*/</lang>
return s==x /*if sum matches X, then it's perfect!*/</syntaxhighlight>
'''output''' &nbsp; is the same as the traditional version &nbsp; and is about &nbsp; '''11.5''' &nbsp; times faster &nbsp; (testing '''34,000,000''' numbers).
'''output''' &nbsp; is the same as the traditional version &nbsp; and is about &nbsp; '''11.5''' &nbsp; times faster &nbsp; (testing '''34,000,000''' numbers).


===Lucas-Lehmer method===
===Lucas-Lehmer method===
This version uses memoization to implement a fast version of the Lucas-Lehmer test.
This version uses memoization to implement a fast version of the Lucas-Lehmer test.
<lang rexx>/*REXX program tests if a number (or a range of numbers) is/are perfect. */
<syntaxhighlight lang="rexx">/*REXX program tests if a number (or a range of numbers) is/are perfect. */
parse arg low high . /*obtain the optional arguments from CL*/
parse arg low high . /*obtain the optional arguments from CL*/
if high=='' & low=="" then high=34000000 /*if no arguments, then use a range. */
if high=='' & low=="" then high=34000000 /*if no arguments, then use a range. */
Line 3,732: Line 3,732:
s=s + j + x%j /*··· add it and the other factor. */
s=s + j + x%j /*··· add it and the other factor. */
end /*j*/ /*(above) is marginally faster. */
end /*j*/ /*(above) is marginally faster. */
return s==x /*if the sum matches X, it's perfect!*/</lang>
return s==x /*if the sum matches X, it's perfect!*/</syntaxhighlight>
'''output''' &nbsp; is the same as the traditional version &nbsp; and is about &nbsp; '''75''' &nbsp; times faster &nbsp; (testing '''34,000,000''' numbers).
'''output''' &nbsp; is the same as the traditional version &nbsp; and is about &nbsp; '''75''' &nbsp; times faster &nbsp; (testing '''34,000,000''' numbers).


Line 3,742: Line 3,742:


An integer square root function was added to limit the factorization of a number.
An integer square root function was added to limit the factorization of a number.
<lang rexx>/*REXX program tests if a number (or a range of numbers) is/are perfect. */
<syntaxhighlight lang="rexx">/*REXX program tests if a number (or a range of numbers) is/are perfect. */
parse arg low high . /*obtain optional arguments from the CL*/
parse arg low high . /*obtain optional arguments from the CL*/
if high=='' & low=="" then high=34000000 /*No arguments? Then use a range. */
if high=='' & low=="" then high=34000000 /*No arguments? Then use a range. */
Line 3,788: Line 3,788:
if x//j==0 then s=s+j+x%j /*J divisible by X? Then add J and X÷J*/
if x//j==0 then s=s+j+x%j /*J divisible by X? Then add J and X÷J*/
end /*j*/
end /*j*/
return s==x /*if the sum matches X, then perfect! */</lang>
return s==x /*if the sum matches X, then perfect! */</syntaxhighlight>
'''output''' &nbsp; is the same as the traditional version &nbsp; and is about &nbsp; '''500''' &nbsp; times faster &nbsp; (testing '''34,000,000''' numbers). <br><br>
'''output''' &nbsp; is the same as the traditional version &nbsp; and is about &nbsp; '''500''' &nbsp; times faster &nbsp; (testing '''34,000,000''' numbers). <br><br>


=={{header|Ring}}==
=={{header|Ring}}==
<lang ring>
<syntaxhighlight lang="ring">
for i = 1 to 10000
for i = 1 to 10000
if perfect(i) see i + nl ok
if perfect(i) see i + nl ok
Line 3,804: Line 3,804:
if sum = n return 1 else return 0 ok
if sum = n return 1 else return 0 ok
return sum
return sum
</syntaxhighlight>
</lang>


=={{header|Ruby}}==
=={{header|Ruby}}==
<lang ruby>def perf(n)
<syntaxhighlight lang="ruby">def perf(n)
sum = 0
sum = 0
for i in 1...n
for i in 1...n
Line 3,813: Line 3,813:
end
end
sum == n
sum == n
end</lang>
end</syntaxhighlight>
Functional style:
Functional style:
<lang ruby>def perf(n)
<syntaxhighlight lang="ruby">def perf(n)
n == (1...n).select {|i| n % i == 0}.inject(:+)
n == (1...n).select {|i| n % i == 0}.inject(:+)
end</lang>
end</syntaxhighlight>
Faster version:
Faster version:
<lang ruby>def perf(n)
<syntaxhighlight lang="ruby">def perf(n)
divisors = []
divisors = []
for i in 1..Integer.sqrt(n)
for i in 1..Integer.sqrt(n)
Line 3,825: Line 3,825:
end
end
divisors.uniq.inject(:+) == 2*n
divisors.uniq.inject(:+) == 2*n
end</lang>
end</syntaxhighlight>
Test:
Test:
<lang ruby>for n in 1..10000
<syntaxhighlight lang="ruby">for n in 1..10000
puts n if perf(n)
puts n if perf(n)
end</lang>
end</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 3,839: Line 3,839:
===Fast (Lucas-Lehmer)===
===Fast (Lucas-Lehmer)===
Generate and memoize perfect numbers as needed.
Generate and memoize perfect numbers as needed.
<lang ruby>require "prime"
<syntaxhighlight lang="ruby">require "prime"


def mersenne_prime_pow?(p)
def mersenne_prime_pow?(p)
Line 3,863: Line 3,863:
p perfect?(13164036458569648337239753460458722910223472318386943117783728128)
p perfect?(13164036458569648337239753460458722910223472318386943117783728128)
p Time.now - t1
p Time.now - t1
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,873: Line 3,873:


=={{header|Run BASIC}}==
=={{header|Run BASIC}}==
<lang runbasic>for i = 1 to 10000
<syntaxhighlight lang="runbasic">for i = 1 to 10000
if perf(i) then print i;" ";
if perf(i) then print i;" ";
next i
next i
Line 3,882: Line 3,882:
next i
next i
IF sum = n THEN perf = 1
IF sum = n THEN perf = 1
END FUNCTION</lang>
END FUNCTION</syntaxhighlight>
{{Out}}
{{Out}}
<pre>6 28 496 8128</pre>
<pre>6 28 496 8128</pre>


=={{header|Rust}}==
=={{header|Rust}}==
<lang rust>
<syntaxhighlight lang="rust">
fn main ( ) {
fn main ( ) {
fn factor_sum(n: i32) -> i32 {
fn factor_sum(n: i32) -> i32 {
Line 3,909: Line 3,909:
perfect_nums(10000);
perfect_nums(10000);
}
}
</syntaxhighlight>
</lang>


=={{header|SASL}}==
=={{header|SASL}}==
Copied from the SASL manual, page 22:
Copied from the SASL manual, page 22:
<syntaxhighlight lang="sasl">
<lang SASL>
|| The function which takes a number and returns a list of its factors (including one but excluding itself)
|| The function which takes a number and returns a list of its factors (including one but excluding itself)
|| can be written
|| can be written
Line 3,920: Line 3,920:
|| we can write the list of all perfect numbers as
|| we can write the list of all perfect numbers as
perfects = { n <- 1... ; n = sum(factors n) }
perfects = { n <- 1... ; n = sum(factors n) }
</syntaxhighlight>
</lang>


=={{header|S-BASIC}}==
=={{header|S-BASIC}}==
<lang basic>
<syntaxhighlight lang="basic">
$lines
$lines


Line 3,963: Line 3,963:


end
end
</syntaxhighlight>
</lang>
{{out}}
{{out}}
<pre>
<pre>
Line 3,975: Line 3,975:


=={{header|Scala}}==
=={{header|Scala}}==
<lang scala>def perfectInt(input: Int) = ((2 to sqrt(input).toInt).collect {case x if input % x == 0 => x + input / x}).sum == input - 1</lang>
<syntaxhighlight lang="scala">def perfectInt(input: Int) = ((2 to sqrt(input).toInt).collect {case x if input % x == 0 => x + input / x}).sum == input - 1</syntaxhighlight>


'''or'''
'''or'''


<lang scala>def perfect(n: Int) =
<syntaxhighlight lang="scala">def perfect(n: Int) =
(for (x <- 2 to n/2 if n % x == 0) yield x).sum + 1 == n
(for (x <- 2 to n/2 if n % x == 0) yield x).sum + 1 == n
</syntaxhighlight>
</lang>


=={{header|Scheme}}==
=={{header|Scheme}}==
<lang scheme>(define (perf n)
<syntaxhighlight lang="scheme">(define (perf n)
(let loop ((i 1)
(let loop ((i 1)
(sum 0))
(sum 0))
Line 3,992: Line 3,992:
(loop (+ i 1) (+ sum i)))
(loop (+ i 1) (+ sum i)))
(else
(else
(loop (+ i 1) sum)))))</lang>
(loop (+ i 1) sum)))))</syntaxhighlight>


=={{header|Seed7}}==
=={{header|Seed7}}==
<lang seed7>$ include "seed7_05.s7i";
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i";


const func boolean: isPerfect (in integer: n) is func
const func boolean: isPerfect (in integer: n) is func
Line 4,026: Line 4,026:
end if;
end if;
end for;
end for;
end func;</lang>
end func;</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 4,037: Line 4,037:


=={{header|Sidef}}==
=={{header|Sidef}}==
<lang ruby>func is_perfect(n) {
<syntaxhighlight lang="ruby">func is_perfect(n) {
n.sigma == 2*n
n.sigma == 2*n
}
}
Line 4,043: Line 4,043:
for n in (1..10000) {
for n in (1..10000) {
say n if is_perfect(n)
say n if is_perfect(n)
}</lang>
}</syntaxhighlight>


Alternatively, a more efficient check for even perfect numbers:
Alternatively, a more efficient check for even perfect numbers:
<lang ruby>func is_even_perfect(n) {
<syntaxhighlight lang="ruby">func is_even_perfect(n) {


var square = (8*n + 1)
var square = (8*n + 1)
Line 4,059: Line 4,059:
for n in (1..10000) {
for n in (1..10000) {
say n if is_even_perfect(n)
say n if is_even_perfect(n)
}</lang>
}</syntaxhighlight>


{{out}}
{{out}}
Line 4,070: Line 4,070:


=={{header|Simula}}==
=={{header|Simula}}==
<lang simula>BOOLEAN PROCEDURE PERF(N); INTEGER N;
<syntaxhighlight lang="simula">BOOLEAN PROCEDURE PERF(N); INTEGER N;
BEGIN
BEGIN
INTEGER SUM;
INTEGER SUM;
Line 4,077: Line 4,077:
SUM := SUM + I;
SUM := SUM + I;
PERF := SUM = N;
PERF := SUM = N;
END PERF;</lang>
END PERF;</syntaxhighlight>


=={{header|Slate}}==
=={{header|Slate}}==
<lang slate>n@(Integer traits) isPerfect
<syntaxhighlight lang="slate">n@(Integer traits) isPerfect
[
[
(((2 to: n // 2 + 1) select: [| :m | (n rem: m) isZero])
(((2 to: n // 2 + 1) select: [| :m | (n rem: m) isZero])
inject: 1 into: #+ `er) = n
inject: 1 into: #+ `er) = n
].</lang>
].</syntaxhighlight>


=={{header|Smalltalk}}==
=={{header|Smalltalk}}==
<lang smalltalk>Integer extend [
<syntaxhighlight lang="smalltalk">Integer extend [


"Translation of the C version; this is faster..."
"Translation of the C version; this is faster..."
Line 4,107: Line 4,107:
inject: 1 into: [ :a :b | a + b ] ) = self
inject: 1 into: [ :a :b | a + b ] ) = self
]
]
].</lang>
].</syntaxhighlight>


<lang smalltalk>1 to: 9000 do: [ :p | (p isPerfect) ifTrue: [ p printNl ] ]</lang>
<syntaxhighlight lang="smalltalk">1 to: 9000 do: [ :p | (p isPerfect) ifTrue: [ p printNl ] ]</syntaxhighlight>


=={{header|Swift}}==
=={{header|Swift}}==
{{trans|Java}}
{{trans|Java}}
<lang Swift>func perfect(n:Int) -> Bool {
<syntaxhighlight lang="swift">func perfect(n:Int) -> Bool {
var sum = 0
var sum = 0
for i in 1..<n {
for i in 1..<n {
Line 4,127: Line 4,127:
println(i)
println(i)
}
}
}</lang>
}</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>
Line 4,137: Line 4,137:


=={{header|Tcl}}==
=={{header|Tcl}}==
<lang tcl>proc perfect n {
<syntaxhighlight lang="tcl">proc perfect n {
set sum 0
set sum 0
for {set i 1} {$i <= $n} {incr i} {
for {set i 1} {$i <= $n} {incr i} {
Line 4,143: Line 4,143:
}
}
expr {$sum == 2*$n}
expr {$sum == 2*$n}
}</lang>
}</syntaxhighlight>


=={{header|Ursala}}==
=={{header|Ursala}}==
<lang Ursala>#import std
<syntaxhighlight lang="ursala">#import std
#import nat
#import nat


is_perfect = ~&itB&& ^(~&,~&t+ iota); ^E/~&l sum:-0+ ~| not remainder</lang>
is_perfect = ~&itB&& ^(~&,~&t+ iota); ^E/~&l sum:-0+ ~| not remainder</syntaxhighlight>
This test program applies the function to a list of the first five hundred natural
This test program applies the function to a list of the first five hundred natural
numbers and deletes the imperfect ones.
numbers and deletes the imperfect ones.
<lang Ursala>#cast %nL
<syntaxhighlight lang="ursala">#cast %nL


examples = is_perfect*~ iota 500</lang>
examples = is_perfect*~ iota 500</syntaxhighlight>
{{Out}}
{{Out}}
<pre><6,28,496></pre>
<pre><6,28,496></pre>
Line 4,161: Line 4,161:
{{trans|Phix}}
{{trans|Phix}}
Using [[Factors_of_an_integer#VBA]], slightly adapted.
Using [[Factors_of_an_integer#VBA]], slightly adapted.
<lang vb>Private Function Factors(x As Long) As String
<syntaxhighlight lang="vb">Private Function Factors(x As Long) As String
Application.Volatile
Application.Volatile
Dim i As Long
Dim i As Long
Line 4,189: Line 4,189:
If is_perfect(i) Then Debug.Print i
If is_perfect(i) Then Debug.Print i
Next i
Next i
End Sub</lang>{{out}}
End Sub</syntaxhighlight>{{out}}
<pre> 6
<pre> 6
28
28
Line 4,196: Line 4,196:


=={{header|VBScript}}==
=={{header|VBScript}}==
<lang vb>Function IsPerfect(n)
<syntaxhighlight lang="vb">Function IsPerfect(n)
IsPerfect = False
IsPerfect = False
i = n - 1
i = n - 1
Line 4,212: Line 4,212:


WScript.StdOut.Write IsPerfect(CInt(WScript.Arguments(0)))
WScript.StdOut.Write IsPerfect(CInt(WScript.Arguments(0)))
WScript.StdOut.WriteLine</lang>
WScript.StdOut.WriteLine</syntaxhighlight>


{{out}}
{{out}}
Line 4,228: Line 4,228:
=={{header|Vlang}}==
=={{header|Vlang}}==
{{trans|go}}
{{trans|go}}
<lang vlang>fn compute_perfect(n i64) bool {
<syntaxhighlight lang="vlang">fn compute_perfect(n i64) bool {
mut sum := i64(0)
mut sum := i64(0)
for i := i64(1); i < n; i++ {
for i := i64(1); i < n; i++ {
Line 4,255: Line 4,255:
}
}
}
}
}</lang>
}</syntaxhighlight>
{{Out}}
{{Out}}
<pre>
<pre>
Line 4,268: Line 4,268:
{{trans|D}}
{{trans|D}}
Restricted to the first four perfect numbers as the fifth one is very slow to emerge.
Restricted to the first four perfect numbers as the fifth one is very slow to emerge.
<lang ecmascript>var isPerfect = Fn.new { |n|
<syntaxhighlight lang="ecmascript">var isPerfect = Fn.new { |n|
if (n <= 2) return false
if (n <= 2) return false
var tot = 1
var tot = 1
Line 4,291: Line 4,291:
i = i + 2 // there are no known odd perfect numbers
i = i + 2 // there are no known odd perfect numbers
}
}
System.print()</lang>
System.print()</syntaxhighlight>


{{out}}
{{out}}
Line 4,301: Line 4,301:
{{libheader|Wren-math}}
{{libheader|Wren-math}}
This makes use of the fact that all known perfect numbers are of the form <big> (2<sup>''n''</sup> - 1) × 2<sup>''n'' - 1</sup></big> where <big> (2<sup>''n''</sup> - 1)</big> is prime and finds the first seven perfect numbers instantly. The numbers are too big after that to be represented accurately by Wren.
This makes use of the fact that all known perfect numbers are of the form <big> (2<sup>''n''</sup> - 1) × 2<sup>''n'' - 1</sup></big> where <big> (2<sup>''n''</sup> - 1)</big> is prime and finds the first seven perfect numbers instantly. The numbers are too big after that to be represented accurately by Wren.
<lang ecmascript>import "/math" for Int
<syntaxhighlight lang="ecmascript">import "/math" for Int


var isPerfect = Fn.new { |n|
var isPerfect = Fn.new { |n|
Line 4,330: Line 4,330:
p = p + 1
p = p + 1
}
}
System.print()</lang>
System.print()</syntaxhighlight>


{{out}}
{{out}}
Line 4,338: Line 4,338:


=={{header|XPL0}}==
=={{header|XPL0}}==
<lang XPL0>include c:\cxpl\codes; \intrinsic 'code' declarations
<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \intrinsic 'code' declarations


func Perfect(N); \Return 'true' if N is a perfect number
func Perfect(N); \Return 'true' if N is a perfect number
Line 4,355: Line 4,355:
if Perfect(N) then [IntOut(0, N); CrLf(0)];
if Perfect(N) then [IntOut(0, N); CrLf(0)];
];
];
]</lang>
]</syntaxhighlight>


{{out}}
{{out}}
Line 4,369: Line 4,369:
=={{header|Yabasic}}==
=={{header|Yabasic}}==
{{trans|True BASIC}}
{{trans|True BASIC}}
<lang basic>
<syntaxhighlight lang="basic">
sub isPerfect(n)
sub isPerfect(n)
if (n < 2) or mod(n, 2) = 1 then return false : endif
if (n < 2) or mod(n, 2) = 1 then return false : endif
Line 4,386: Line 4,386:
print
print
end
end
</syntaxhighlight>
</lang>




=={{header|Zig}}==
=={{header|Zig}}==
<syntaxhighlight lang="zig">
<lang Zig>
const std = @import("std");
const std = @import("std");
const expect = std.testing.expect;
const expect = std.testing.expect;
Line 4,420: Line 4,420:
expect(propersum(30) == 42);
expect(propersum(30) == 42);
}
}
</syntaxhighlight>
</lang>
{{Out}}
{{Out}}
<pre>
<pre>
Line 4,427: Line 4,427:
=={{header|zkl}}==
=={{header|zkl}}==
{{trans|D}}
{{trans|D}}
<lang zkl>fcn isPerfectNumber1(n)
<syntaxhighlight lang="zkl">fcn isPerfectNumber1(n)
{ n == [1..n-1].filter('wrap(i){ n % i == 0 }).sum(); }</lang>
{ n == [1..n-1].filter('wrap(i){ n % i == 0 }).sum(); }</syntaxhighlight>
{{out}}
{{out}}
<pre>
<pre>