Perfect totient numbers: Difference between revisions

m
syntax highlighting fixup automation
(Added implementation in D)
m (syntax highlighting fixup automation)
Line 15:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F φ(n)
R sum((1..n).filter(k -> gcd(@n, k) == 1).map(k -> 1))
 
Line 32:
R r
 
print(perfect_totient(20))</langsyntaxhighlight>
 
{{out}}
Line 40:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program totientPerfect64.s */
Line 166:
/***************************************************/
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
<pre>
3 9 15 27 39
Line 174:
</pre>
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">BEGIN # find the first 20 perfect totient numbers #
# returns the number of integers k where 1 <= k <= n that are mutually prime to n #
PROC totient = ( INT n )INT: # algorithm from the second Go sample #
Line 212:
OD;
print( ( newline ) )
END</langsyntaxhighlight>
{{out}}
<pre>
Line 219:
 
=={{header|APL}}==
<langsyntaxhighlight APLlang="apl">(⊢(/⍨)((+/((1+.=⍳∨⊢)∘⊃,⊢)⍣(1=(⊃⊣)))=2∘×)¨)1↓⍳6000</langsyntaxhighlight>
{{out}}
<pre>3 9 15 27 39 81 111 183 243 255 327 363 471 729 2187 2199 3063 4359 4375 5571</pre>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI or android with termux */
/* program totientPerfect.s */
Line 349:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
</lang>
<pre>
3 9 15 27 39
Line 358:
=={{header|Arturo}}==
{{trans|Nim}}
<langsyntaxhighlight lang="rebol">totient: function [n][
tt: new n
nn: new n
Line 397:
'x + 2
]
print ""</langsyntaxhighlight>
 
{{out}}
Line 404:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox, 262144, , % result := perfect_totient(20)
 
perfect_totient(n){
Line 438:
tot -= tot / n
return tot
}</langsyntaxhighlight>
{{out}}
<pre>3, 9, 15, 27, 39, 81, 111, 183, 243, 255, 327, 363, 471, 729, 2187, 2199, 3063, 4359, 4375, 5571</pre>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f PERFECT_TOTIENT_NUMBERS.AWK
BEGIN {
Line 483:
return(tot)
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 491:
 
=={{header|BASIC}}==
<langsyntaxhighlight BASIClang="basic">10 DEFINT A-Z
20 N=3
30 S=N: T=0
Line 504:
120 IF T=N THEN PRINT N,: Z=Z+1
130 N=N+2
140 IF Z<20 GOTO 30</langsyntaxhighlight>
{{out}}
<pre> 3 9 15 27 39
Line 513:
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="freebasic">found = 0
curr = 3
 
Line 544:
next m
return phi
end function</langsyntaxhighlight>
 
 
=={{header|bc}}==
<langsyntaxhighlight lang="bc">define gcd (i, j) {
while(j != 0) {
k = j
Line 581:
print "\n"
quit
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 594:
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let gcd(a,b) = b=0 -> a, gcd(b, a rem b)
Line 623:
$)
wrch('*N')
$)</langsyntaxhighlight>
{{out}}
<pre>3 9 15 27 39 81 111 183 243 255 327 363 471 729 2187 2199 3063 4359 4375 5571</pre>
Line 629:
=={{header|C}}==
Calculates as many perfect Totient numbers as entered on the command line.
<langsyntaxhighlight Clang="c">#include<stdlib.h>
#include<stdio.h>
 
Line 689:
return 0;
}
</syntaxhighlight>
</lang>
Output for multiple runs, a is the default executable file name produced by GCC
<pre>
Line 707:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <cassert>
#include <iostream>
#include <vector>
Line 758:
std::cout << '\n';
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 766:
</pre>
=={{header|CLU}}==
<langsyntaxhighlight lang="clu">gcd = proc (a, b: int) returns (int)
while b ~= 0 do
a, b := b, a//b
Line 803:
n := n + 2
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>3 9 15 27 39 81 111 183 243 255 327 363 471 729 2187 2199 3063 4359 4375 5571</pre>
=={{header|Cowgol}}==
<langsyntaxhighlight lang="cowgol">include "cowgol.coh";
 
sub gcd(a: uint16, b: uint16): (r: uint16) is
Line 848:
n := n + 2;
end loop;
print_nl();</langsyntaxhighlight>
{{out}}
<pre>3 9 15 27 39 81 111 183 243 255 327 363 471 729 2187 2199 3063 4359 4375 5571</pre>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio;
import std.numeric;
 
Line 882:
writeln(" ");
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 890:
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">import "dart:io";
 
var cache = List<int>.filled(10000, 0, growable: true);
Line 919:
return n == sum;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 928:
{{libheader| System.SysUtils}}
{{Trans|Go}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Perfect_totient_numbers;
 
Line 982:
writeln(']');
readln;
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 989:
 
=={{header|Draco}}==
<langsyntaxhighlight lang="draco">proc nonrec gcd(word a, b) word:
word c;
while b ~= 0 do
Line 1,031:
n := n + 2
od
corp</langsyntaxhighlight>
{{out}}
<pre>3 9 15 27 39 81 111 183 243 255 327 363 471 729 2187 2199 3063 4359 4375 5571</pre>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: formatting kernel lists lists.lazy math
math.primes.factors ;
 
Line 1,044:
 
20 1 lfrom [ perfect? ] lfilter ltake list>array
"%[%d, %]\n" printf</langsyntaxhighlight>
{{out}}
<pre>
Line 1,053:
Uses the code from the [[Totient_function#FreeBASIC|Totient Function]] example as an include.
 
<langsyntaxhighlight lang="freebasic">#include"totient.bas"
 
dim as uinteger found = 0, curr = 3, sum, toti
Line 1,069:
end if
curr += 1
wend</langsyntaxhighlight>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,131:
fmt.Println("The first 20 perfect totient numbers are:")
fmt.Println(perfect)
}</langsyntaxhighlight>
 
{{out}}
Line 1,140:
 
The following much quicker version uses Euler's product formula rather than repeated invocation of the gcd function to calculate the totient:
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,178:
fmt.Println("The first 20 perfect totient numbers are:")
fmt.Println(perfect)
}</langsyntaxhighlight>
 
The output is the same as before.
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">perfectTotients :: [Int]
perfectTotients =
filter ((==) <*> (succ . sum . tail . takeWhile (1 /=) . iterate φ)) [2 ..]
Line 1,194:
 
main :: IO ()
main = print $ take 20 perfectTotients</langsyntaxhighlight>
{{Out}}
<pre>[3,9,15,27,39,81,111,183,243,255,327,363,471,729,2187,2199,3063,4359,4375,5571]</pre>
 
=={{header|J}}==
<syntaxhighlight lang="j">
<lang J>
Until =: conjunction def 'u^:(0 -: v)^:_'
Filter =: (#~`)(`:6)
Line 1,205:
totient_chain =: [: }. (, totient@{:)Until(1={:)
ptnQ =: (= ([: +/ totient_chain))&>
</syntaxhighlight>
</lang>
With these definitions I've found the first 28 perfect totient numbers
<pre>
Line 1,216:
 
=={{header|Java}}==
<syntaxhighlight lang="java">
<lang Java>
import java.util.ArrayList;
import java.util.List;
Line 1,262:
 
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,270:
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">(() => {
'use strict';
 
Line 1,404:
// MAIN ---
main();
})();</langsyntaxhighlight>
{{Out}}
<pre>[3,9,15,27,39,81,111,183,243,255,327,363,471,729,2187,2199,3063,4359,4375,5571]</pre>
Line 1,415:
One small point of interest in the following implementation is the way the
cacheing of totient values is accomplished using a helper function (`cachephi`).
<syntaxhighlight lang="jq">
<lang jq>
# jq optimizes the recursive call of _gcd in the following:
def gcd(a;b):
Line 1,450:
 
"The first 20 perfect totient numbers:",
limit(20; perfect_totients)</langsyntaxhighlight>
{{out}}
<pre>
Line 1,477:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Primes
 
eulerphi(n) = (r = one(n); for (p,k) in factor(abs(n)) r *= p^(k-1)*(p-1) end; r)
Line 1,505:
println("The first 20 perfect totient numbers are: $(perfecttotientseries(20))")
println("The first 40 perfect totient numbers are: $(perfecttotientseries(40))")
</langsyntaxhighlight>{{output}}<pre>
The first 20 perfect totient numbers are: [3, 9, 15, 27, 39, 81, 111, 183, 243, 255, 327, 363, 471, 729, 2187, 2199, 3063, 4359, 4375, 5571]
The first 40 perfect totient numbers are: [3, 9, 15, 27, 39, 81, 111, 183, 243, 255, 327, 363, 471, 729, 2187, 2199, 3063, 4359, 4375, 5571, 6561, 8751, 15723, 19683, 36759, 46791, 59049, 65535, 140103, 177147, 208191, 441027, 531441, 1594323, 4190263, 4782969, 9056583, 14348907, 43046721, 57395631]
Line 1,512:
=={{header|Kotlin}}==
{{trans|Go}}
<langsyntaxhighlight lang="scala">// Version 1.3.21
 
fun totient(n: Int): Int {
Line 1,545:
println("The first 20 perfect totient numbers are:")
println(perfect)
}</langsyntaxhighlight>
 
{{output}}
Line 1,554:
 
=={{header|Lua}}==
<langsyntaxhighlight Lualang="lua">local function phi(n)
assert(type(n) == 'number', 'n must be a number!')
local result, i = n, 2
Line 1,586:
i = i + 1
end
</syntaxhighlight>
</lang>
 
{{output}}
Line 1,594:
 
=={{header|MAD}}==
<langsyntaxhighlight MADlang="mad"> NORMAL MODE IS INTEGER
INTERNAL FUNCTION(Y,Z)
Line 1,633:
 
VECTOR VALUES FMT = $I9*$
END OF PROGRAM </langsyntaxhighlight>
{{out}}
<pre> 3
Line 1,657:
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">iterated_totient := proc(n::posint, total)
if NumberTheory:-Totient(n) = 1 then
return total + 1;
Line 1,675:
end if;
end do;
num_list;</langsyntaxhighlight>
{{output}}
<pre>
Line 1,682:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">ClearAll[PerfectTotientNumberQ]
PerfectTotientNumberQ[n_Integer] := Total[Rest[Most[FixedPointList[EulerPhi, n]]]] == n
res = {};
Line 1,690:
If[PerfectTotientNumberQ[i], AppendTo[res, i]]
]
res</langsyntaxhighlight>
{{out}}
<pre>{3,9,15,27,39,81,111,183,243,255,327,363,471,729,2187,2199,3063,4359,4375,5571}</pre>
 
=={{header|Modula-2}}==
<langsyntaxhighlight lang="modula2">MODULE PerfectTotient;
FROM InOut IMPORT WriteCard, WriteLn;
 
Line 1,750:
END;
WriteLn();
END PerfectTotient.</langsyntaxhighlight>
{{out}}
<pre> 3 9 15 27 39 81 111 183 243 255 327 363 471 729
Line 1,756:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import strformat
 
func totient(n: int): int =
Line 1,787:
inc num
inc n, 2
write(stdout, "\n")</langsyntaxhighlight>
{{out}}
<pre>
Line 1,802:
The c-program takes "real 3m12,481s"<BR>
A test with using floating point/SSE is by 2 seconds faster for 46.th perfect totient number, with the coming new Version of Freepascal 3.2.0
<langsyntaxhighlight lang="pascal">program Perftotient;
{$IFdef FPC}
{$MODE DELPHI} {$CodeAlign proc=32,loop=1}
Line 1,958:
write(Sollist[j],',');
end;
end.</langsyntaxhighlight>
;OutPut:
<pre>compiled with fpc 3.0.4 -O3 "Perftotient.pas"
Line 1,982:
=={{header|Perl}}==
{{libheader|ntheory}}
<langsyntaxhighlight lang="perl">use ntheory qw(euler_phi);
 
sub phi_iter {
Line 1,994:
}
 
printf "The first twenty perfect totient numbers:\n%s\n", join ' ', @perfect;</langsyntaxhighlight>
{{out}}
<pre>The first twenty Perfect totient numbers:
Line 2,001:
=={{header|Phix}}==
{{trans|Go}}
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">totient</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
Line 2,037:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"The first 20 perfect totient numbers are:\n"</span><span style="color: #0000FF;">)</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">perfect</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,045:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(gc 16)
(de gcd (A B)
(until (=0 B)
Line 2,068:
(inc 'N 2) ) )
(prinl) ) )
(totients)</langsyntaxhighlight>
{{out}}
<pre>
Line 2,075:
 
=={{header|PILOT}}==
<langsyntaxhighlight lang="pilot">C :z=0
:n=3
*num
Line 2,101:
C :n=n+2
J (z<20):*num
E :</langsyntaxhighlight>
{{out}}
<pre>3
Line 2,125:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">perfectTotient: procedure options(main);
gcd: procedure(aa, bb) returns(fixed);
declare (aa, bb, a, b, c) fixed;
Line 2,167:
end;
end;
end perfectTotient;</langsyntaxhighlight>
{{out}}
<pre> 3 9 15 27 39 81 111 183 243 255
Line 2,173:
 
=={{header|PL/M}}==
<langsyntaxhighlight lang="plm">100H:
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
Line 2,231:
END;
CALL EXIT;
EOF</langsyntaxhighlight>
{{out}}
<pre>3 9 15 27 39 81 111 183 243 255 327 363 471 729 2187 2199 3063 4359 4375 5571</pre>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">from math import gcd
from functools import lru_cache
from itertools import islice, count
Line 2,255:
 
if __name__ == '__main__':
print(list(islice(perfect_totient(), 20)))</langsyntaxhighlight>
 
{{out}}
Line 2,263:
Alternatively, by composition of generic functions:
 
<langsyntaxhighlight lang="python">'''Perfect totient numbers'''
 
from functools import lru_cache
Line 2,362:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>[3, 9, 15, 27, 39, 81, 111, 183, 243, 255, 327, 363, 471, 729, 2187, 2199, 3063, 4359, 4375, 5571]</pre>
Line 2,370:
<code>totient</code> is defined at [[Totient function#Quackery]].
 
<langsyntaxhighlight Quackerylang="quackery"> [ 0 over
[ dup 1 != while
totient
Line 2,383:
over size 20 =
until ] drop ] is task ( --> )
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,390:
 
=={{header|Racket}}==
<syntaxhighlight lang="racket">
<lang Racket>
#lang racket
(require math/number-theory)
Line 2,411:
 
(reverse ns)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 2,417:
{{works with|Rakudo|2018.11}}
 
<syntaxhighlight lang="raku" perl6line>use Prime::Factor;
 
my \𝜑 = lazy 0, |(1..*).hyper.map: -> \t { t * [*] t.&prime-factors.squish.map: 1 - 1/* }
my \𝜑𝜑 = Nil, |(3, *+2 … *).grep: -> \p { p == sum 𝜑[p], { 𝜑[$_] } … 1 };
 
put "The first twenty Perfect totient numbers:\n", 𝜑𝜑[1..20];</langsyntaxhighlight>
{{out}}
<pre>The first twenty Perfect totient numbers:
Line 2,429:
=={{header|REXX}}==
===unoptimized===
<langsyntaxhighlight lang="rexx">/*REXX program calculates and displays the first N perfect totient numbers. */
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 20 /*Not specified? Then use the default.*/
Line 2,452:
phi: procedure expose @.; parse arg z; if @.z\==. then return @.z /*was found before?*/
#= z==1; do m=1 for z-1; if gcd(m, z)==1 then #= # + 1; end /*m*/
@.z= #; return # /*use memoization. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input of : &nbsp; &nbsp; <tt> 20 </tt>}}
<pre>
Line 2,465:
 
('''3<sup>22</sup>''' &nbsp; '''=''' &nbsp; '''31,381,059,609''').
<langsyntaxhighlight lang="rexx">/*REXX program calculates and displays the first N perfect totient numbers. */
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 20 /*Not specified? Then use the default.*/
Line 2,490:
phi: procedure expose @.; parse arg z; if @.z\==. then return @.z /*was found before?*/
#= z==1; do m=1 for z-1; if gcd(m, z)==1 then #= # + 1; end /*m*/
@.z= #; return # /*use memoization. */</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 1<sup>st</sup> REXX version.}} <br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
perfect = []
n = 1
Line 2,545:
txt = txt + "]"
see txt
</syntaxhighlight>
</lang>
<pre>
The first 20 perfect totient numbers are:
Line 2,552:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require "prime"
 
class Integer
Line 2,572:
 
puts (1..).lazy.select(&:perfect_totient?).first(20).join(", ")
</syntaxhighlight>
</lang>
{{Out}}
<pre>3, 9, 15, 27, 39, 81, 111, 183, 243, 255, 327, 363, 471, 729, 2187, 2199, 3063, 4359, 4375, 5571
Line 2,579:
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use num::integer::gcd;
 
static mut CACHE:[i32;10000] = [0; 10000];
Line 2,609:
println!("{}", " ")
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>3 9 15 27 39 81 111 183 243 255 327 363 471 729 2187 2199 3063 4359 4375 5571
Line 2,617:
 
In this example we define a function which determines whether or not a number is a perfect totient number, then use it to construct a lazily evaluated list which contains all perfect totient numbers. Calculating the first n perfect totient numbers only requires taking the first n elements from the list.
<langsyntaxhighlight lang="scala">//List of perfect totients
def isPerfectTotient(num: Int): Boolean = LazyList.iterate(totient(num))(totient).takeWhile(_ != 1).foldLeft(0L)(_+_) + 1 == num
def perfectTotients: LazyList[Int] = LazyList.from(3).filter(isPerfectTotient)
Line 2,623:
//Totient Function
@tailrec def scrub(f: Long, num: Long): Long = if(num%f == 0) scrub(f, num/f) else num
def totient(num: Long): Long = LazyList.iterate((num, 2: Long, num)){case (ac, i, n) => if(n%i == 0) (ac*(i - 1)/i, i + 1, scrub(i, n)) else (ac, i + 1, n)}.dropWhile(_._3 != 1).head._1</langsyntaxhighlight>
 
{{out}}
Line 2,630:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func perfect_totient({.<=1}, sum=0) { sum }
func perfect_totient( n, sum=0) { __FUNC__(var(t = n.euler_phi), sum + t) }
 
say (1..Inf -> lazy.grep {|n| perfect_totient(n) == n }.first(20))</langsyntaxhighlight>
{{out}}
<pre>
Line 2,641:
=={{header|Swift}}==
 
<langsyntaxhighlight lang="swift">public func totient(n: Int) -> Int {
var n = n
var i = 2
Line 2,696:
 
print("The first 20 perfect totient numbers are:")
print(Array(PerfectTotients().prefix(20)))</langsyntaxhighlight>
 
{{out}}
Line 2,706:
=={{header|Tcl}}==
 
<langsyntaxhighlight lang="tcl">array set cache {}
 
set cache(0) 0
Line 2,742:
}
puts ""
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,756:
{{trans|Go}}
The version using Euler's product formula.
<langsyntaxhighlight lang="ecmascript">var totient = Fn.new { |n|
var tot = n
var i = 2
Line 2,784:
}
System.print("The first 20 perfect totient numbers are:")
System.print(perfect)</langsyntaxhighlight>
 
{{out}}
Line 2,793:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">var totients=List.createLong(10_000,0); // cache
fcn totient(n){ if(phi:=totients[n]) return(phi);
totients[n]=[1..n].reduce('wrap(p,k){ p + (n.gcd(k)==1) })
Line 2,803:
if(parts==z) z else Void.Skip;
})
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">perfectTotientW().walk(20).println();</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits