Totient function: Difference between revisions
Content deleted Content added
m →{{header|Wren}}: Minor tidy |
|||
(38 intermediate revisions by 17 users not shown) | |||
Line 49:
{{trans|Python}}
<
R sum((1..n).filter(k -> gcd(@n, k) == 1).map(k -> 1))
Line 61:
count += is_prime(n)
I n C (100, 1000, 10'000)
print(‘Primes up to #.: #.’.format(n, count))</
{{out}}
Line 94:
Primes up to 10000: 1229
</pre>
=={{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">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program totient.s */
/************************************/
/* Constantes */
/************************************/
.include "../includeConstantesARM64.inc"
.equ MAXI, 25
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessNumber: .asciz " number @ totient @ @ \n"
szCarriageReturn: .asciz "\n"
szMessPrime: .asciz " is prime."
szMessSpace: .asciz " "
szMessCounterPrime: .asciz "Number of primes to @ : @ \n"
szMessOverflow: .asciz "Overflow function isPrime.\n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main:
mov x4,#1 // start number
1:
mov x0,x4
bl totient // compute totient
mov x5,x0
mov x0,x4
bl isPrime // control if number is prime
mov x6,x0
mov x0,x4 // display result
ldr x1,qAdrsZoneConv
bl conversion10 // call décimal conversion
ldr x0,qAdrszMessNumber
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
mov x7,x0
mov x0,x5
ldr x1,qAdrsZoneConv
bl conversion10 // call décimal conversion
mov x0,x7
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
mov x7,x0
cmp x6,#1
ldr x1,qAdrszMessPrime
ldr x8,qAdrszMessSpace
csel x1,x1,x8,eq
mov x0,x7
bl strInsertAtCharInc
bl affichageMess // display message
add x4,x4,#1 // increment number
cmp x4,#MAXI // maxi ?
ble 1b // and loop
mov x4,#2 // first number
mov x5,#0 // prime counter
ldr x6,iCst1000 // load constantes
ldr x7,iCst10000
ldr x8,iCst100000
2:
mov x0,x4
bl isPrime
cmp x0,#0
beq 3f
add x5,x5,#1
3:
add x4,x4,#1
cmp x4,#100
bne 4f
mov x0,#100
mov x1,x5
bl displayCounter
b 7f
4:
cmp x4,x6 // 1000
bne 5f
mov x0,x6
mov x1,x5
bl displayCounter
b 7f
5:
cmp x4,x7 // 10000
bne 6f
mov x0,x7
mov x1,x5
bl displayCounter
b 7f
6:
cmp x4,x8 // 100000
bne 7f
mov x0,x8
mov x1,x5
bl displayCounter
7:
cmp x4,x8
ble 2b // and loop
100: // standard end of the program
mov x0, #0 // return code
mov x8,EXIT
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsZoneConv: .quad sZoneConv
qAdrszMessNumber: .quad szMessNumber
qAdrszMessCounterPrime: .quad szMessCounterPrime
qAdrszMessPrime: .quad szMessPrime
qAdrszMessSpace: .quad szMessSpace
iCst1000: .quad 1000
iCst10000: .quad 10000
iCst100000: .quad 100000
/******************************************************************/
/* display counter */
/******************************************************************/
/* x0 contains limit */
/* x1 contains counter */
displayCounter:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x1
ldr x1,qAdrsZoneConv
bl conversion10 // call décimal conversion
ldr x0,qAdrszMessCounterPrime
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
mov x3,x0
mov x0,x2
ldr x1,qAdrsZoneConv
bl conversion10 // call décimal conversion
mov x0,x3
ldr x1,qAdrsZoneConv // insert conversion in message
bl strInsertAtCharInc
bl affichageMess
100:
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
/******************************************************************/
/* compute totient of number */
/******************************************************************/
/* x0 contains number */
totient:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x4,x0 // totient
mov x5,x0 // save number
mov x1,#0 // for first divisor
1: // begin loop
mul x3,x1,x1 // compute square
cmp x3,x5 // compare number
bgt 4f // end
add x1,x1,#2 // next divisor
udiv x2,x5,x1
msub x3,x1,x2,x5 // compute remainder
cmp x3,#0 // remainder null ?
bne 3f
2: // begin loop 2
udiv x2,x5,x1
msub x3,x1,x2,x5 // compute remainder
cmp x3,#0
csel x5,x2,x5,eq // new value = quotient
beq 2b
udiv x2,x4,x1 // divide totient
sub x4,x4,x2 // compute new totient
3:
cmp x1,#2 // first divisor ?
mov x0,1
csel x1,x0,x1,eq // divisor = 1
b 1b // and loop
4:
cmp x5,#1 // final value > 1
ble 5f
mov x0,x4 // totient
mov x1,x5 // divide by value
udiv x2,x4,x5 // totient divide by value
sub x4,x4,x2 // compute new totient
5:
mov x0,x4
100:
ldp x4,x5,[sp],16 // restaur registers
ldp x2,x3,[sp],16 // restaur registers
ldp x1,lr,[sp],16 // restaur registers
ret
/***************************************************/
/* Verification si un nombre est premier */
/***************************************************/
/* x0 contient le nombre à verifier */
/* x0 retourne 1 si premier 0 sinon */
isPrime:
stp x1,lr,[sp,-16]! // save registres
stp x2,x3,[sp,-16]! // save registres
mov x2,x0
sub x1,x0,#1
cmp x2,0
beq 99f // retourne zéro
cmp x2,2 // pour 1 et 2 retourne 1
ble 2f
mov x0,#2
bl moduloPur64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,3
beq 2f
mov x0,#3
bl moduloPur64
blt 100f // erreur overflow
cmp x0,#1
bne 99f
cmp x2,5
beq 2f
mov x0,#5
bl moduloPur64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,7
beq 2f
mov x0,#7
bl moduloPur64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,11
beq 2f
mov x0,#11
bl moduloPur64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,13
beq 2f
mov x0,#13
bl moduloPur64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
cmp x2,17
beq 2f
mov x0,#17
bl moduloPur64
bcs 100f // erreur overflow
cmp x0,#1
bne 99f // Pas premier
2:
cmn x0,0 // carry à zero pas d'erreur
mov x0,1 // premier
b 100f
99:
cmn x0,0 // carry à zero pas d'erreur
mov x0,#0 // Pas premier
100:
ldp x2,x3,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
/**************************************************************/
/********************************************************/
/* Calcul modulo de b puissance e modulo m */
/* Exemple 4 puissance 13 modulo 497 = 445 */
/********************************************************/
/* x0 nombre */
/* x1 exposant */
/* x2 modulo */
moduloPur64:
stp x1,lr,[sp,-16]! // save registres
stp x3,x4,[sp,-16]! // save registres
stp x5,x6,[sp,-16]! // save registres
stp x7,x8,[sp,-16]! // save registres
stp x9,x10,[sp,-16]! // save registres
cbz x0,100f
cbz x1,100f
mov x8,x0
mov x7,x1
mov x6,1 // resultat
udiv x4,x8,x2
msub x9,x4,x2,x8 // contient le reste
1:
tst x7,1
beq 2f
mul x4,x9,x6
umulh x5,x9,x6
//cbnz x5,99f
mov x6,x4
mov x0,x6
mov x1,x5
bl divisionReg128U
cbnz x1,99f // overflow
mov x6,x3
2:
mul x8,x9,x9
umulh x5,x9,x9
mov x0,x8
mov x1,x5
bl divisionReg128U
cbnz x1,99f // overflow
mov x9,x3
lsr x7,x7,1
cbnz x7,1b
mov x0,x6 // result
cmn x0,0 // carry à zero pas d'erreur
b 100f
99:
ldr x0,qAdrszMessOverflow
bl affichageMess
cmp x0,0 // carry à un car erreur
mov x0,-1 // code erreur
100:
ldp x9,x10,[sp],16 // restaur des 2 registres
ldp x7,x8,[sp],16 // restaur des 2 registres
ldp x5,x6,[sp],16 // restaur des 2 registres
ldp x3,x4,[sp],16 // restaur des 2 registres
ldp x1,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
qAdrszMessOverflow: .quad szMessOverflow
/***************************************************/
/* division d un nombre de 128 bits par un nombre de 64 bits */
/***************************************************/
/* x0 contient partie basse dividende */
/* x1 contient partie haute dividente */
/* x2 contient le diviseur */
/* x0 retourne partie basse quotient */
/* x1 retourne partie haute quotient */
/* x3 retourne le reste */
divisionReg128U:
stp x6,lr,[sp,-16]! // save registres
stp x4,x5,[sp,-16]! // save registres
mov x5,#0 // raz du reste R
mov x3,#128 // compteur de boucle
mov x4,#0 // dernier bit
1:
lsl x5,x5,#1 // on decale le reste de 1
tst x1,1<<63 // test du bit le plus à gauche
lsl x1,x1,#1 // on decale la partie haute du quotient de 1
beq 2f
orr x5,x5,#1 // et on le pousse dans le reste R
2:
tst x0,1<<63
lsl x0,x0,#1 // puis on decale la partie basse
beq 3f
orr x1,x1,#1 // et on pousse le bit de gauche dans la partie haute
3:
orr x0,x0,x4 // position du dernier bit du quotient
mov x4,#0 // raz du bit
cmp x5,x2
blt 4f
sub x5,x5,x2 // on enleve le diviseur du reste
mov x4,#1 // dernier bit à 1
4:
// et boucle
subs x3,x3,#1
bgt 1b
lsl x1,x1,#1 // on decale le quotient de 1
tst x0,1<<63
lsl x0,x0,#1 // puis on decale la partie basse
beq 5f
orr x1,x1,#1
5:
orr x0,x0,x4 // position du dernier bit du quotient
mov x3,x5
100:
ldp x4,x5,[sp],16 // restaur des 2 registres
ldp x6,lr,[sp],16 // restaur des 2 registres
ret // retour adresse lr x30
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../includeARM64.inc"
</syntaxhighlight>
<pre>
number 1 totient 1 is prime.
number 2 totient 1 is prime.
number 3 totient 2 is prime.
number 4 totient 2
number 5 totient 4 is prime.
number 6 totient 2
number 7 totient 6 is prime.
number 8 totient 4
number 9 totient 6
number 10 totient 4
number 11 totient 10 is prime.
number 12 totient 4
number 13 totient 12 is prime.
number 14 totient 6
number 15 totient 8
number 16 totient 8
number 17 totient 16 is prime.
number 18 totient 6
number 19 totient 18 is prime.
number 20 totient 8
number 21 totient 12
number 22 totient 10
number 23 totient 22 is prime.
number 24 totient 8
number 25 totient 20
Number of primes to 100 : 25
Number of primes to 1000 : 168
Number of primes to 10000 : 1229
Number of primes to 100000 : 9592
</pre>
=={{header|Ada}}==
{{trans|C}}
<
with Ada.Integer_Text_IO;
Line 169 ⟶ 591:
end loop;
end Totient;</
{{out}}
Line 216 ⟶ 638:
{{Trans|Go}}
Uses the totient algorithm from the second Go sample.
<
# returns the number of integers k where 1 <= k <= n that are mutually prime to n #
PROC totient = ( INT n )INT:
Line 242 ⟶ 664:
FOR n TO 25 DO
INT tn = totient( n );
print( ( whole( n, -2 ), ": ", whole( tn, -5
, IF tn = n - 1 AND tn /= 0 THEN " n is prime" ELSE "" FI, newline
)
)
OD;
# use the totient function to count primes #
Line 258 ⟶ 683:
print( ( "There are ", whole( n10000, -6 ), " primes below 10 000", newline ) );
print( ( "There are ", whole( n100000, -6 ), " primes below 100 000", newline ) )
END</
{{out}}
<pre>
Line 291 ⟶ 716:
There are 1229 primes below 10 000
There are 9592 primes below 100 000
</pre>
=={{header|ALGOL-M}}==
The GCD approach is straight-forward and easy to follow, but is not particularly efficient.
<syntaxhighlight lang="algol">
BEGIN
% RETURN P MOD Q %
INTEGER FUNCTION MOD (P, Q);
INTEGER P, Q;
BEGIN
MOD := P - Q * (P / Q);
END;
% RETURN GREATEST COMMON DIVISOR OF X AND Y %
INTEGER FUNCTION GCD (X, Y);
INTEGER X, Y;
BEGIN
INTEGER R;
IF X < Y THEN
BEGIN
INTEGER TEMP;
TEMP := X;
X := Y;
Y := TEMP;
END;
WHILE (R := MOD(X, Y)) <> 0 DO
BEGIN
X := Y;
Y := R;
END;
GCD := Y;
END;
% RETURN PHI (ALSO CALLED TOTIENT) OF N %
INTEGER FUNCTION PHI(N);
INTEGER N;
BEGIN
INTEGER I, COUNT;
COUNT := 1;
FOR I := 2 STEP 1 UNTIL N DO
BEGIN
IF GCD(N,I) = 1 THEN COUNT := COUNT + 1;
END;
PHI := COUNT;
END;
COMMENT - EXERCISE THE FUNCTION;
INTEGER N, TOTIENT, COUNT;
WRITE(" N PHI(N) PRIME?");
FOR N := 1 STEP 1 UNTIL 25 DO
BEGIN
WRITE(N, (TOTIENT := PHI(N)));
WRITEON(IF TOTIENT = (N-1) THEN " YES" ELSE " NO");
END;
COMMENT - AND USE IT TO COUNT PRIMES;
WRITE("");
COUNT := 0;
FOR N := 1 STEP 1 UNTIL 1000 DO
BEGIN
IF PHI(N) = (N-1) THEN COUNT := COUNT + 1;
IF N = 100 THEN
WRITE("PRIMES UP TO 100 =", COUNT)
ELSE IF N = 1000 THEN
WRITE("PRIMES UP TO 1000 =", COUNT);
END;
END
</syntaxhighlight>
{{out}}
Limiting the search to 1000 keeps the running time of the program within reasonable bounds.
<pre>
N PHI(N) PRIME?
1 1 NO
2 1 YES
3 2 YES
4 2 NO
5 4 YES
6 2 NO
7 6 YES
8 4 NO
9 6 NO
10 4 NO
11 10 YES
12 4 NO
13 12 YES
14 6 NO
15 8 NO
16 8 NO
17 16 YES
18 6 NO
19 18 YES
20 8 NO
21 12 NO
22 10 NO
23 22 YES
24 8 NO
25 20 NO
PRIMES UP TO 100 = 25
PRIMES UP TO 1000 = 168
</pre>
=={{header|APL}}==
{{works with|Dyalog APL}}
<
totient ← 1+.=⍳∨⊢
prime ← totient=-∘1
Line 301 ⟶ 829:
⎕←'Index' 'Totient' 'Prime',(⊢⍪totient¨,[÷2]prime¨)⍳25
{⎕←'There are' (+/prime¨⍳⍵) 'primes below' ⍵}¨100 1000 10000
}</
{{out}}
<pre> Index 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Line 309 ⟶ 837:
There are 168 primes below 1000
There are 1229 primes below 10000</pre>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI or android with termux */
/* program totient.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
.equ MAXI, 25
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessNumber: .asciz " number @ totient @ @ \n"
szCarriageReturn: .asciz "\n"
szMessPrime: .asciz " is prime."
szMessSpace: .asciz " "
szMessCounterPrime: .asciz "Number of primes to @ : @ \n"
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main:
mov r4,#1 @ start number
1:
mov r0,r4
bl totient @ compute totient
mov r5,r0
mov r0,r4
bl isPrime @ control if number is prime
mov r6,r0
mov r0,r4 @ display result
ldr r1,iAdrsZoneConv
bl conversion10 @ call décimal conversion
ldr r0,iAdrszMessNumber
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
mov r7,r0
mov r0,r5
ldr r1,iAdrsZoneConv
bl conversion10 @ call décimal conversion
mov r0,r7
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
mov r7,r0
cmp r6,#1
ldreq r1,iAdrszMessPrime
ldrne r1,iAdrszMessSpace
mov r0,r7
bl strInsertAtCharInc
bl affichageMess @ display message
add r4,r4,#1 @ increment number
cmp r4,#MAXI @ maxi ?
ble 1b @ and loop
mov r4,#2 @ first number
mov r5,#0 @ prime counter
ldr r6,iCst1000 @ load constantes
ldr r7,iCst10000
ldr r8,iCst100000
2:
mov r0,r4
bl isPrime
cmp r0,#0
beq 3f
add r5,r5,#1
3:
add r4,r4,#1
cmp r4,#100
bne 4f
mov r0,#100
mov r1,r5
bl displayCounter
b 7f
4:
cmp r4,r6 @ 1000
bne 5f
mov r0,r6
mov r1,r5
bl displayCounter
b 7f
5:
cmp r4,r7 @ 10000
bne 6f
mov r0,r7
mov r1,r5
bl displayCounter
b 7f
6:
cmp r4,r8 @ 100000
bne 7f
mov r0,r8
mov r1,r5
bl displayCounter
7:
cmp r4,r8
ble 2b @ and loop
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsZoneConv: .int sZoneConv
iAdrszMessNumber: .int szMessNumber
iAdrszMessCounterPrime: .int szMessCounterPrime
iAdrszMessPrime: .int szMessPrime
iAdrszMessSpace: .int szMessSpace
iCst1000: .int 1000
iCst10000: .int 10000
iCst100000: .int 100000
/******************************************************************/
/* display counter */
/******************************************************************/
/* r0 contains limit */
/* r1 contains counter */
displayCounter:
push {r1-r3,lr} @ save registers
mov r2,r1
ldr r1,iAdrsZoneConv
bl conversion10 @ call décimal conversion
ldr r0,iAdrszMessCounterPrime
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
mov r3,r0
mov r0,r2
ldr r1,iAdrsZoneConv
bl conversion10 @ call décimal conversion
mov r0,r3
ldr r1,iAdrsZoneConv @ insert conversion in message
bl strInsertAtCharInc
bl affichageMess
100:
pop {r1-r3,pc} @ restaur registers
/******************************************************************/
/* compute totient of number */
/******************************************************************/
/* r0 contains number */
totient:
push {r1-r5,lr} @ save registers
mov r4,r0 @ totient
mov r5,r0 @ save number
mov r1,#0 @ for first divisor
1: @ begin loop
mul r3,r1,r1 @ compute square
cmp r3,r5 @ compare number
bgt 4f @ end
add r1,r1,#2 @ next divisor
mov r0,r5
bl division
cmp r3,#0 @ remainder null ?
bne 3f
2: @ begin loop 2
mov r0,r5
bl division
cmp r3,#0
moveq r5,r2 @ new value = quotient
beq 2b
mov r0,r4 @ totient
bl division
sub r4,r4,r2 @ compute new totient
3:
cmp r1,#2 @ first divisor ?
moveq r1,#1 @ divisor = 1
b 1b @ and loop
4:
cmp r5,#1 @ final value > 1
ble 5f
mov r0,r4 @ totient
mov r1,r5 @ divide by value
bl division
sub r4,r4,r2 @ compute new totient
5:
mov r0,r4
100:
pop {r1-r5,pc} @ restaur registers
/***************************************************/
/* check if a number is prime */
/***************************************************/
/* r0 contains the number */
/* r0 return 1 if prime 0 else */
@2147483647
@4294967297
@131071
isPrime:
push {r1-r6,lr} @ save registers
cmp r0,#0
beq 90f
cmp r0,#17
bhi 1f
cmp r0,#3
bls 80f @ for 1,2,3 return prime
cmp r0,#5
beq 80f @ for 5 return prime
cmp r0,#7
beq 80f @ for 7 return prime
cmp r0,#11
beq 80f @ for 11 return prime
cmp r0,#13
beq 80f @ for 13 return prime
cmp r0,#17
beq 80f @ for 17 return prime
1:
tst r0,#1 @ even ?
beq 90f @ yes -> not prime
mov r2,r0 @ save number
sub r1,r0,#1 @ exposant n - 1
mov r0,#3 @ base
bl moduloPuR32 @ compute base power n - 1 modulo n
cmp r0,#1
bne 90f @ if <> 1 -> not prime
mov r0,#5
bl moduloPuR32
cmp r0,#1
bne 90f
mov r0,#7
bl moduloPuR32
cmp r0,#1
bne 90f
mov r0,#11
bl moduloPuR32
cmp r0,#1
bne 90f
mov r0,#13
bl moduloPuR32
cmp r0,#1
bne 90f
mov r0,#17
bl moduloPuR32
cmp r0,#1
bne 90f
80:
mov r0,#1 @ is prime
b 100f
90:
mov r0,#0 @ no prime
100: @ fin standard de la fonction
pop {r1-r6,lr} @ restaur des registres
bx lr @ retour de la fonction en utilisant lr
/********************************************************/
/* Calcul modulo de b puissance e modulo m */
/* Exemple 4 puissance 13 modulo 497 = 445 */
/* */
/********************************************************/
/* r0 nombre */
/* r1 exposant */
/* r2 modulo */
/* r0 return result */
moduloPuR32:
push {r1-r7,lr} @ save registers
cmp r0,#0 @ verif <> zero
beq 100f
cmp r2,#0 @ verif <> zero
beq 100f @ TODO: vérifier les cas erreur
1:
mov r4,r2 @ save modulo
mov r5,r1 @ save exposant
mov r6,r0 @ save base
mov r3,#1 @ start result
mov r1,#0 @ division de r0,r1 par r2
bl division32R
mov r6,r2 @ base <- remainder
2:
tst r5,#1 @ exposant even or odd
beq 3f
umull r0,r1,r6,r3
mov r2,r4
bl division32R
mov r3,r2 @ result <- remainder
3:
umull r0,r1,r6,r6
mov r2,r4
bl division32R
mov r6,r2 @ base <- remainder
lsr r5,#1 @ left shift 1 bit
cmp r5,#0 @ end ?
bne 2b
mov r0,r3
100: @ fin standard de la fonction
pop {r1-r7,lr} @ restaur des registres
bx lr @ retour de la fonction en utilisant lr
/***************************************************/
/* division number 64 bits in 2 registers by number 32 bits */
/***************************************************/
/* r0 contains lower part dividende */
/* r1 contains upper part dividende */
/* r2 contains divisor */
/* r0 return lower part quotient */
/* r1 return upper part quotient */
/* r2 return remainder */
division32R:
push {r3-r9,lr} @ save registers
mov r6,#0 @ init upper upper part remainder !!
mov r7,r1 @ init upper part remainder with upper part dividende
mov r8,r0 @ init lower part remainder with lower part dividende
mov r9,#0 @ upper part quotient
mov r4,#0 @ lower part quotient
mov r5,#32 @ bits number
1: @ begin loop
lsl r6,#1 @ shift upper upper part remainder
lsls r7,#1 @ shift upper part remainder
orrcs r6,#1
lsls r8,#1 @ shift lower part remainder
orrcs r7,#1
lsls r4,#1 @ shift lower part quotient
lsl r9,#1 @ shift upper part quotient
orrcs r9,#1
@ divisor sustract upper part remainder
subs r7,r2
sbcs r6,#0 @ and substract carry
bmi 2f @ négative ?
@ positive or equal
orr r4,#1 @ 1 -> right bit quotient
b 3f
2: @ negative
orr r4,#0 @ 0 -> right bit quotient
adds r7,r2 @ and restaur remainder
adc r6,#0
3:
subs r5,#1 @ decrement bit size
bgt 1b @ end ?
mov r0,r4 @ lower part quotient
mov r1,r9 @ upper part quotient
mov r2,r7 @ remainder
100: @ function end
pop {r3-r9,lr} @ restaur registers
bx lr
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
<pre>
number 1 totient 1 is prime.
number 2 totient 1 is prime.
number 3 totient 2 is prime.
number 4 totient 2
number 5 totient 4 is prime.
number 6 totient 2
number 7 totient 6 is prime.
number 8 totient 4
number 9 totient 6
number 10 totient 4
number 11 totient 10 is prime.
number 12 totient 4
number 13 totient 12 is prime.
number 14 totient 6
number 15 totient 8
number 16 totient 8
number 17 totient 16 is prime.
number 18 totient 6
number 19 totient 18 is prime.
number 20 totient 8
number 21 totient 12
number 22 totient 10
number 23 totient 22 is prime.
number 24 totient 8
number 25 totient 20
Number of primes to 100 : 25
Number of primes to 1000 : 168
Number of primes to 10000 : 1229
Number of primes to 100000 : 9592
</pre>
=={{header|Arturo}}==
<syntaxhighlight lang="arturo">totient: function [n][
tot: new n
i: 2
while -> n >= i * i [
if 0 = n % i [
while -> 0 = n % i -> n: n / i
'tot - tot / i
]
if 2 = i -> i: 1
'i + 2
]
if n > 1 -> 'tot - tot / n
return tot
]
primes: 0
loop 1..100000 'i [
t: totient i
prime?: 1 = i - t
if i < 26 [
prints ~« Φ(|pad.with:`0` to :string i 2|) = |pad to :string t 2|
if prime? -> prints ", prime"
print ""
]
if 50 = i -> print ""
if in? i [100 1000 10000 100000] -> print ~« |primes| primes =< |i|
if prime? -> 'primes + 1
]</syntaxhighlight>
{{out}}
<pre>Φ(01) = 1
Φ(02) = 1, prime
Φ(03) = 2, prime
Φ(04) = 2
Φ(05) = 4, prime
Φ(06) = 2
Φ(07) = 6, prime
Φ(08) = 4
Φ(09) = 6
Φ(10) = 4
Φ(11) = 10, prime
Φ(12) = 4
Φ(13) = 12, prime
Φ(14) = 6
Φ(15) = 8
Φ(16) = 8
Φ(17) = 16, prime
Φ(18) = 6
Φ(19) = 18, prime
Φ(20) = 8
Φ(21) = 12
Φ(22) = 10
Φ(23) = 22, prime
Φ(24) = 8
Φ(25) = 20
25 primes =< 100
168 primes =< 1000
1229 primes =< 10000
9592 primes =< 100000</pre>
=={{header|AutoHotkey}}==
<syntaxhighlight lang="autohotkey">
global cptext := a_tab "Nr" a_tab "Phi" a_tab "Prime?`n---------------------------------------------`n"
divisores(num)
{
serie := ""
loop % num
if !mod(num,a_index)
serie .= a_index ","
return serie
}
gcd(serieA,serieB)
{
emComum := 0
loop,parse,serieA,csv
if A_LoopField in %serieB%
emComum += 1
return emComum
}
principal(voltas,phi:=0)
{
loop %voltas%
{
cp := A_Index
cpcount := 0
numA := divisores(cp)
loop % a_index
{
numA := divisores(cp)
numB := divisores(A_Index)
fim := gcd(numA,numB)
if (fim = 1)
cpcount += 1
}
if (cpcount = cp-1)
{
if phi
cptext .= a_tab cp a_tab cpcount a_tab "1`n"
totalPrimes += 1
}
else
cptext .= a_tab cp a_tab cpcount a_tab "0`n"
}
return totalPrimes
}
totalPrimes := principal(25,1)
msgbox % cptext "`n`ntotal primes = " totalPrimes ; Number 1 is a prime number ? If yes, add 1 to totalPrimes
totalPrimes := principal(100)
msgbox % "total primes in 1 .. 100 = " totalPrimes
totalPrimes := principal(1000) ; caution... pure gcd method
msgbox % "total primes in 1 .. 1000 = " totalPrimes ; takes 3 minutes or more
;totalPrimes := principal(10000)
;msgbox % "total primes in 1 .. 10000 = " totalPrimes
ExitApp
</syntaxhighlight>
{{Out}}
<pre>
---------------------------
Totient function.ahk
---------------------------
Nr Phi Prime?
---------------------------------------------
1 1 0
2 1 1
3 2 1
4 2 0
5 4 1
6 2 0
7 6 1
8 4 0
9 6 0
10 4 0
11 10 1
12 4 0
13 12 1
14 6 0
15 8 0
16 8 0
17 16 1
18 6 0
19 18 1
20 8 0
21 12 0
22 10 0
23 22 1
24 8 0
25 20 0
total primes = 9
---------------------------
OK
---------------------------
total primes in 1 .. 100 = 25
---------------------------
OK
---------------------------
total primes in 1 .. 1000 = 168
---------------------------
OK
</pre>
=={{header|AWK}}==
<syntaxhighlight lang="awk">
# syntax: GAWK -f TOTIENT_FUNCTION.AWK
BEGIN {
Line 351 ⟶ 1,440:
return(tot)
}
</syntaxhighlight>
{{out}}
<pre>
Line 389 ⟶ 1,478:
1000000 78498
</pre>
=={{header|BASIC}}==
<syntaxhighlight lang="gwbasic">10 DEFINT A-Z: DIM B$(2): B$(0)="No": B$(1)="Yes"
20 PRINT " N Totient Prime"
30 FOR N=1 TO 25
40 GOSUB 200
50 P=-(T=N-1)
60 C=C+P
70 PRINT USING "## ####### \ \";N;T;B$(P)
80 NEXT N
90 F$="Number of primes up to ######: ####"
100 PRINT USING F$;25;C
110 FOR N=26 TO 10000
120 GOSUB 200
130 C=C-(T=N-1)
140 IF N=100 OR N=1000 OR N=10000 THEN PRINT USING F$;N;C
150 NEXT N
160 END
200 REM T = TOTIENT(N)
210 T=N: Z=N
220 I=2: GOSUB 270
230 I=3
240 IF I*I<=Z THEN GOSUB 270: I=I+2: GOTO 240
250 IF Z>1 THEN T=T-T\Z
260 RETURN
270 IF Z MOD I<>0 THEN RETURN
280 IF Z MOD I=0 THEN Z = Z\I: GOTO 280
290 T = T-T\I
300 RETURN</syntaxhighlight>
{{out}}
<pre> N Totient Prime
1 1 No
2 1 Yes
3 2 Yes
4 2 No
5 4 Yes
6 2 No
7 6 Yes
8 4 No
9 6 No
10 4 No
11 10 Yes
12 4 No
13 12 Yes
14 6 No
15 8 No
16 8 No
17 16 Yes
18 6 No
19 18 Yes
20 8 No
21 12 No
22 10 No
23 22 Yes
24 8 No
25 20 No
Number of primes up to 25: 9
Number of primes up to 100: 25
Number of primes up to 1000: 168
Number of primes up to 10000: 1229</pre>
=={{header|BCPL}}==
{{trans|C}}
<syntaxhighlight lang="bcpl">get "libhdr"
let totient(n) = valof
$( let tot = n and i = 2
while i*i <= n
$( if n rem i = 0
$( while n rem i = 0 do n := n / i
tot := tot - tot/i
$)
if i=2 then i:=1
i := i+2
$)
resultis n>1 -> tot-tot/n, tot
$)
let start() be
$( let count = 0
writes(" N Totient Prime*N")
for n = 1 to 25
$( let tot = totient(n)
let prime = n-1 = tot
if prime then count := count + 1
writef("%I2 %I7 %S*N", n, tot, prime -> " Yes", " No")
$)
writef("Number of primes up to %I6: %I4*N", 25, count)
for n = 26 to 10000
$( if totient(n) = n-1 then count := count + 1
if n = 100 | n = 1000 | n = 10000 then
writef("Number of primes up to %I6: %I4*N", n, count)
$)
$)</syntaxhighlight>
{{out}}
<pre> N Totient Prime
1 1 No
2 1 Yes
3 2 Yes
4 2 No
5 4 Yes
6 2 No
7 6 Yes
8 4 No
9 6 No
10 4 No
11 10 Yes
12 4 No
13 12 Yes
14 6 No
15 8 No
16 8 No
17 16 Yes
18 6 No
19 18 Yes
20 8 No
21 12 No
22 10 No
23 22 Yes
24 8 No
25 20 No
Number of primes up to 25: 9
Number of primes up to 100: 25
Number of primes up to 1000: 168
Number of primes up to 10000: 1229</pre>
=={{header|BQN}}==
GCD function is taken from BQNcrate.
The totient function is similar to APL and J, except it is made as a train. An explicit version of <code>Totient</code> is <code>{+´1=𝕩GCD¨1+↕𝕩}</code>
<syntaxhighlight lang="bqn">GCD ← {𝕨(|𝕊⍟(>⟜0)⊣)𝕩}
Totient ← +´1=⊢GCD¨1+↕</syntaxhighlight>
{{out|Usage}}
<syntaxhighlight lang="bqn"> Totient¨1+↕25
⟨ 1 1 2 2 4 2 6 4 6 4 10 4 12 6 8 8 16 6 18 8 12 10 22 8 20 ⟩
"Number"‿"Totient"‿"Prime?"∾˘{𝕩∾(⊢≍(𝕩-1)⊸=)Totient¨𝕩}1+↕25
┌─
╵ "Number" 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
"Totient" 1 1 2 2 4 2 6 4 6 4 10 4 12 6 8 8 16 6 18 8 12 10 22 8 20
"Prime?" 0 1 1 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 1 0 0 0 1 0 0
┘</syntaxhighlight>
The [https://github.com/mlochbaum/bqn-libs/blob/master/primes.bqn primes] library from bqn-libs includes a <code>Totient</code> function based on factoring that's much faster for numbers in the hundreds and above.
=={{header|C}}==
Translation of the second Go example
<syntaxhighlight lang="c">
/*Abhishek Ghosh, 7th December 2018*/
Line 447 ⟶ 1,680:
return 0;
}
</syntaxhighlight>
Output :
Line 507 ⟶ 1,740:
=={{header|C sharp}}==
<
using static System.Linq.Enumerable;
Line 544 ⟶ 1,777:
return totient;
}
}</
{{out}}
<pre style="height:30ex;overflow:scroll">
Line 581 ⟶ 1,814:
=={{header|C++}}==
{{trans|Java}}
<
#include <iomanip>
#include <iostream>
Line 632 ⟶ 1,865:
}
return 0;
}</
{{out}}
Line 669 ⟶ 1,902:
Count of primes up to 10000000: 664579
</pre>
=={{header|CLU}}==
{{trans|C}}
<syntaxhighlight lang="clu">totient = proc (n: int) returns (int)
tot: int := n
i: int := 2
while i*i <= n do
if n//i = 0 then
while n//i = 0 do
n := n/i
end
tot := tot-tot/i
end
if i=2 then i:=1 end
i := i+2
end
if n>1 then
tot := tot-tot/n
end
return(tot)
end totient
start_up = proc ()
po: stream := stream$primary_output()
count: int := 0
stream$putl(po, " N Totient Prime")
for n: int in int$from_to(1, 25) do
tot: int := totient(n)
stream$putright(po, int$unparse(n), 2)
stream$putright(po, int$unparse(tot), 9)
if n-1 = tot then
stream$putright(po, "Yes", 7)
count := count + 1
else
stream$putright(po, "No", 7)
end
stream$putl(po, "")
end
stream$putl(po, "Number of primes up to 25:\t" || int$unparse(count))
for n: int in int$from_to(26, 100000) do
if totient(n) = n-1 then
count := count + 1
end
if n = 100 cor n = 1000 cor n // 10000 = 0 then
stream$putl(po, "Number of primes up to "
|| int$unparse(n) || ":\t"
|| int$unparse(count))
end
end
end start_up</syntaxhighlight>
{{out}}
<pre> N Totient Prime
1 1 No
2 1 Yes
3 2 Yes
4 2 No
5 4 Yes
6 2 No
7 6 Yes
8 4 No
9 6 No
10 4 No
11 10 Yes
12 4 No
13 12 Yes
14 6 No
15 8 No
16 8 No
17 16 Yes
18 6 No
19 18 Yes
20 8 No
21 12 No
22 10 No
23 22 Yes
24 8 No
25 20 No
Number of primes up to 25: 9
Number of primes up to 100: 25
Number of primes up to 1000: 168
Number of primes up to 10000: 1229
Number of primes up to 20000: 2262
Number of primes up to 30000: 3245
Number of primes up to 40000: 4203
Number of primes up to 50000: 5133
Number of primes up to 60000: 6057
Number of primes up to 70000: 6935
Number of primes up to 80000: 7837
Number of primes up to 90000: 8713
Number of primes up to 100000: 9592</pre>
=={{header|COBOL}}==
<syntaxhighlight lang="cobol"> IDENTIFICATION DIVISION.
PROGRAM-ID. TOTIENT-FUNCTION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 TOTIENT-CALCULATION.
03 N PIC 9(6).
03 TOTIENT PIC 9(6).
03 DIVISOR PIC 9(6).
03 DIV-SQUARE PIC 9(6).
03 MODULUS PIC 9(6).
01 LOOP-VARS.
03 PRIME-COUNT PIC 9(4).
03 CURRENT-N PIC 9(6).
03 PRIME-TOTIENT PIC 9(6).
01 OUTPUTFORMAT.
03 HEADER PIC X(20) VALUE " N Totient Prime?".
03 TOTIENT-ROW.
05 OUT-N PIC Z9.
05 FILLER PIC XX VALUE SPACES.
05 OUT-TOTIENT PIC Z(6)9.
05 FILLER PIC XX VALUE SPACES.
05 OUT-PRIME PIC X(5).
03 PRIME-COUNT-ROW.
05 FILLER PIC X(22) VALUE "Number of primes up to".
05 OUT-PRMTO PIC Z(5)9.
05 FILLER PIC XX VALUE ": ".
05 OUT-PRMCNT PIC ZZZ9.
PROCEDURE DIVISION.
BEGIN.
MOVE ZERO TO PRIME-COUNT.
DISPLAY HEADER.
PERFORM SHOW-SMALL-TOTIENT
VARYING CURRENT-N FROM 1 BY 1
UNTIL CURRENT-N IS GREATER THAN 25.
MOVE 25 TO OUT-PRMTO.
MOVE PRIME-COUNT TO OUT-PRMCNT.
DISPLAY PRIME-COUNT-ROW.
PERFORM COUNT-PRIMES
VARYING CURRENT-N FROM 26 BY 1
UNTIL CURRENT-N IS GREATER THAN 10000.
STOP RUN.
SHOW-SMALL-TOTIENT.
MOVE CURRENT-N TO N.
PERFORM CALCULATE-TOTIENT.
MOVE CURRENT-N TO OUT-N.
MOVE TOTIENT TO OUT-TOTIENT.
MOVE "No" TO OUT-PRIME.
SUBTRACT 1 FROM CURRENT-N GIVING PRIME-TOTIENT.
IF TOTIENT IS EQUAL TO PRIME-TOTIENT,
MOVE "Yes" TO OUT-PRIME,
ADD 1 TO PRIME-COUNT.
DISPLAY TOTIENT-ROW.
COUNT-PRIMES.
MOVE CURRENT-N TO N.
PERFORM CALCULATE-TOTIENT.
SUBTRACT 1 FROM CURRENT-N GIVING PRIME-TOTIENT.
IF TOTIENT IS EQUAL TO PRIME-TOTIENT, ADD 1 TO PRIME-COUNT.
IF CURRENT-N IS EQUAL TO 100 OR 1000 OR 10000,
MOVE CURRENT-N TO OUT-PRMTO,
MOVE PRIME-COUNT TO OUT-PRMCNT,
DISPLAY PRIME-COUNT-ROW.
CALCULATE-TOTIENT.
MOVE N TO TOTIENT.
MOVE 2 TO DIVISOR.
MOVE 4 TO DIV-SQUARE.
PERFORM DIVIDE-STEP.
PERFORM DIVIDE-STEP
VARYING DIVISOR FROM 3 BY 2
UNTIL DIV-SQUARE IS GREATER THAN N.
IF N IS GREATER THAN 1,
COMPUTE TOTIENT = TOTIENT - TOTIENT / N.
DIVIDE-STEP.
MULTIPLY DIVISOR BY DIVISOR GIVING DIV-SQUARE.
DIVIDE N BY DIVISOR GIVING MODULUS.
MULTIPLY DIVISOR BY MODULUS.
SUBTRACT MODULUS FROM N GIVING MODULUS.
IF MODULUS IS ZERO,
PERFORM DIVIDE-OUT UNTIL MODULUS IS NOT ZERO,
COMPUTE TOTIENT = TOTIENT - TOTIENT / DIVISOR.
DIVIDE-OUT.
DIVIDE DIVISOR INTO N.
DIVIDE N BY DIVISOR GIVING MODULUS.
MULTIPLY DIVISOR BY MODULUS.
SUBTRACT MODULUS FROM N GIVING MODULUS.</syntaxhighlight>
{{out}}
<pre> N Totient Prime?
1 1 No
2 1 Yes
3 2 Yes
4 2 No
5 4 Yes
6 2 No
7 6 Yes
8 4 No
9 6 No
10 4 No
11 10 Yes
12 4 No
13 12 Yes
14 6 No
15 8 No
16 8 No
17 16 Yes
18 6 No
19 18 Yes
20 8 No
21 12 No
22 10 No
23 22 Yes
24 8 No
25 20 No
Number of primes up to 25: 9
Number of primes up to 100: 25
Number of primes up to 1000: 168
Number of primes up to 10000: 1229</pre>
=={{header|Cowgol}}==
{{trans|C}}
<syntaxhighlight lang="cowgol">include "cowgol.coh";
sub totient(n: uint32): (tot: uint32) is
tot := n;
var i: uint32 := 2;
while i*i <= n loop
if n%i == 0 then
while n%i == 0 loop
n := n/i;
end loop;
tot := tot - tot/i;
end if;
if i == 2 then
i := 1;
end if;
i := i + 2;
end loop;
if n > 1 then
tot := tot - tot/n;
end if;
end sub;
var count: uint16 := 0;
print("N\tTotient\tPrime\n");
var n: uint32 := 1;
while n <= 25 loop
var tot := totient(n);
print_i32(n);
print_char('\t');
print_i32(tot);
print_char('\t');
if n-1 == tot then
count := count + 1;
print("Yes\n");
else
print("No\n");
end if;
n := n + 1;
end loop;
print("Number of primes up to 25:\t");
print_i16(count);
print_nl();
while n <= 100000 loop
tot := totient(n);
if n-1 == tot then
count := count + 1;
end if;
if n == 100 or n == 1000 or n % 10000 == 0 then
print("Number of primes up to ");
print_i32(n);
print(":\t");
print_i16(count);
print_nl();
end if;
n := n + 1;
end loop;</syntaxhighlight>
{{out}}
<pre>N Totient Prime
1 1 No
2 1 Yes
3 2 Yes
4 2 No
5 4 Yes
6 2 No
7 6 Yes
8 4 No
9 6 No
10 4 No
11 10 Yes
12 4 No
13 12 Yes
14 6 No
15 8 No
16 8 No
17 16 Yes
18 6 No
19 18 Yes
20 8 No
21 12 No
22 10 No
23 22 Yes
24 8 No
25 20 No
Number of primes up to 25: 9
Number of primes up to 100: 25
Number of primes up to 1000: 168
Number of primes up to 10000: 1229
Number of primes up to 20000: 2262
Number of primes up to 30000: 3245
Number of primes up to 40000: 4203
Number of primes up to 50000: 5133
Number of primes up to 60000: 6057
Number of primes up to 70000: 6935
Number of primes up to 80000: 7837
Number of primes up to 90000: 8713
Number of primes up to 100000: 9592</pre>
=={{header|D}}==
{{trans|C}}
<
int totient(int n) {
Line 723 ⟶ 2,279:
}
}
}</
{{out}}
<pre> n φ prime
Line 769 ⟶ 2,325:
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Totient_function#Pascal Pascal].
=={{header|Draco}}==
{{trans|C}}
<syntaxhighlight lang="draco">proc totient(word n) word:
word tot, i;
tot := n;
i := 2;
while i*i <= n do
if n%i = 0 then
while n%i = 0 do n := n/i od;
tot := tot - tot/i
fi;
if i=2 then i:=1 fi;
i := i+2
od;
if n>1 then
tot - tot/n
else
tot
fi
corp
proc main() void:
word count, n, tot;
bool prime;
count := 0;
writeln(" N Totient Prime");
for n from 1 upto 25 do
tot := totient(n);
prime := n-1 = tot;
if prime then count := count+1 fi;
writeln(n:2, " ", tot:7, " ", if prime then " Yes" else " No" fi)
od;
writeln("Number of primes up to ",25:6,": ",count:4);
for n from 25 upto 10000 do
if totient(n) = n-1 then count := count+1 fi;
if n=100 or n=1000 or n=10000 then
writeln("Number of primes up to ",n:6,": ",count:4)
fi
od
corp</syntaxhighlight>
{{out}}
<pre> N Totient Prime
1 1 No
2 1 Yes
3 2 Yes
4 2 No
5 4 Yes
6 2 No
7 6 Yes
8 4 No
9 6 No
10 4 No
11 10 Yes
12 4 No
13 12 Yes
14 6 No
15 8 No
16 8 No
17 16 Yes
18 6 No
19 18 Yes
20 8 No
21 12 No
22 10 No
23 22 Yes
24 8 No
25 20 No
Number of primes up to 25: 9
Number of primes up to 100: 25
Number of primes up to 1000: 168
Number of primes up to 10000: 1229</pre>
=={{header|Dyalect}}==
Line 774 ⟶ 2,403:
{{trans|Go}}
<
var tot = n
var i = 2
Line 814 ⟶ 2,443:
print("Number of primes up to \(n) \t= \(count)")
}
}</
{{out}}
Line 858 ⟶ 2,487:
Number of primes up to 90000 = 8713
Number of primes up to 100000 = 9592</pre>
=={{header|EasyLang}}==
{{trans|AWK}}
<syntaxhighlight lang="easylang">
func totient n .
tot = n
i = 2
while i <= sqrt n
if n mod i = 0
while n mod i = 0
n = n div i
.
tot -= tot div i
.
if i = 2
i = 1
.
i += 2
.
if n > 1
tot -= tot div n
.
return tot
.
numfmt 0 3
print " N Prim Phi"
for n = 1 to 25
tot = totient n
x$ = " "
if n - 1 = tot
x$ = " x "
.
print n & x$ & tot
.
print ""
for n = 1 to 100000
tot = totient n
if n - 1 = tot
cnt += 1
.
if n = 100 or n = 1000 or n = 10000 or n = 100000
print n & " - " & cnt & " primes"
.
.
</syntaxhighlight>
=={{header|Factor}}==
<
math.ranges sequences ;
IN: rosetta-code.totient-function
Line 885 ⟶ 2,560:
] each drop ;
MAIN: totient-demo</
{{out}}
<pre>
Line 922 ⟶ 2,597:
=={{header|FreeBASIC}}==
{{trans|Pascal}}
<
#define esPar(n) (((n) And 1) = 0)
#define esImpar(n) (esPar(n) = 0)
Line 1,033 ⟶ 2,708:
Loop Until l > 1000000
End
</syntaxhighlight>
{{out}}
<pre>
Line 1,074 ⟶ 2,749:
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/Euler%27s_totient_function}}
'''Solution'''
[[File:Fōrmulæ - Totient function 01.png]]
'''Case 1'''
[[File:Fōrmulæ - Totient function 02.png]]
[[File:Fōrmulæ - Totient function 03.png]]
'''Case 2'''
[[File:Fōrmulæ - Totient function 04.png]]
[[File:Fōrmulæ - Totient function 05.png]]
=={{header|Forth}}==
Translation from C
<syntaxhighlight lang="forth">
: totient \ n -- n' ;
DUP DUP 2 ?DO ( tot n )
DUP I DUP * < IF LEAVE THEN \ for(i=2;i*i<=n;i+=2){
DUP I MOD 0= IF \ if(n%i==0){
BEGIN DUP I /MOD SWAP 0= WHILE ( tot n n/i ) \ while(n%i==0);
NIP ( tot n/i ) \ n/=i;
REPEAT
DROP ( tot n ) \ Remove the new n on exit from loop
SWAP DUP I / - SWAP ( tot' n ) \ tot-=tot/i;
THEN
2 I 2 = + +LOOP \ If I = 2 add 1 else add 2 to loop index.
DUP 1 > IF OVER SWAP / - ELSE DROP THEN ;
: bool. \ f -- ;
IF ." True " ELSE ." False" THEN ;
: count-primes \ n -- n' ;
0 SWAP 2 ?DO I DUP totient 1+ = - LOOP ;
: challenge \ -- ;
CR ." n φ prime" CR
26 1 DO
I 3 .r
I totient DUP 4 .r 4 SPACES
1+ I = bool. CR
LOOP CR
100001 100 DO
." Number of primes up to " I 6 .R ." is " I count-primes 4 .R CR
I 9 * +LOOP ;
</syntaxhighlight>
{{out}}
<pre>challenge
n φ prime
1 1 False
2 1 True
3 2 True
4 2 False
5 4 True
6 2 False
7 6 True
8 4 False
9 6 False
10 4 False
11 10 True
12 4 False
13 12 True
14 6 False
15 8 False
16 8 False
17 16 True
18 6 False
19 18 True
20 8 False
21 12 False
22 10 False
23 22 True
24 8 False
25 20 False
Number of primes up to 100 is 25
Number of primes up to 1000 is 168
Number of primes up to 10000 is 1229
Number of primes up to 100000 is 9592
</pre>
=={{header|Go}}==
Results for the larger values of n are very slow to emerge.
<
import "fmt"
Line 1,148 ⟶ 2,905:
}
}
}</
{{out}}
Line 1,209 ⟶ 2,966:
The following much quicker version (runs in less than 150 ms on my machine) uses Euler's product formula rather than repeated invocation of the gcd function to calculate the totient:
<
import "fmt"
Line 1,254 ⟶ 3,011:
}
}
}</
The output is the same as before.
Line 1,260 ⟶ 3,017:
=={{header|Haskell}}==
{{trans|C}}
<
import Control.Monad (when)
Line 1,308 ⟶ 3,065:
putStrLn $ "Number of primes up to " ++ show i_ ++ " = " ++ show count_
loop (i + 1) count_
loop 0 0</
{{out}}
<pre>
Line 1,347 ⟶ 3,104:
=={{header|J}}==
<syntaxhighlight lang="j">
nth_prime =: p: NB. 2 is the zeroth prime
totient =: 5&p:
Line 1,375 ⟶ 3,132:
100000 9592
1e6 78498
</syntaxhighlight>
=={{header|Java}}==
Efficiently pre-compute all needed values of phi up to 10,000,000 in .344 sec.
<
public class TotientFunction {
Line 1,421 ⟶ 3,178:
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,461 ⟶ 3,218:
=={{header|jq}}==
{{works with|jq}}
<syntaxhighlight lang="jq">
# jq optimizes the recursive call of _gcd in the following:
def gcd(a;b):
Line 1,478 ⟶ 3,235:
def primes_via_totient:
range(0; .) | select(totient == . - 1);
</syntaxhighlight>
'''The tasks'''
<
def task1($n):
range(1;$n)
Line 1,498 ⟶ 3,255:
else . end else . end else . end) ;
task, "\nCounts of primes up to the given limits:", onepass</
{{out}}
<pre>
Line 1,533 ⟶ 3,290:
=={{header|Julia}}==
{{trans|Python}}
<
is_prime(n) = φ(n) == n - 1
Line 1,551 ⟶ 3,308:
runphitests()
</
φ(1) == 1
φ(2) == 1, is prime
Line 1,585 ⟶ 3,342:
=={{header|Kotlin}}==
{{trans|Go}}
<
fun totient(n: Int): Int {
Line 1,621 ⟶ 3,378:
}
}
}</
{{output}}
Line 1,630 ⟶ 3,387:
=={{header|Lua}}==
Averages about 7 seconds under LuaJIT
<
function gcd (x, y)
return y == 0 and math.abs(x) or gcd(y, x % y)
Line 1,665 ⟶ 3,422:
until i == limit
print("\nThere are " .. pCount .. " primes below " .. limit)
end</
{{out}}
<pre>n φ prime
Line 1,701 ⟶ 3,458:
There are 1229 primes below 10000</pre>
Alternative, faster version - around 0.04 seconds using LuaJIT on TIO.RUN.
{{Trans|ALGOL 68|so using the totient algorithm from the second Go sample}}
<syntaxhighlight lang="lua">
do
function totient( n ) -- returns the number of integers k where 1 <= k <= n that are mutually prime to n
if n < 3 then return 1
elseif n == 3 then return 2
else
local result, v, i = n, n, 2
while i * i <= v do
if v % i == 0 then
while v % i == 0 do v = math.floor( v / i ) end
result = result - math.floor( result / i )
end
if i == 2 then
i = 1
end
i = i + 2
end
if v > 1 then result = result - math.floor( result / v ) end
return result
end
end
-- show the totient function values for the first 25 integers
io.write( " n phi(n) remarks\n" )
for n = 1,25 do
local tn = totient( n )
io.write( string.format( "%2d", n ), ": ", string.format( "%5d", tn )
, ( tn == n - 1 and tn ~= 0 and " n is prime" or "" )
, "\n"
)
end
-- use the totient function to count primes
local n100, n1000, n10000, n100000 = 0, 0, 0, 0
for n = 1,100000 do
if totient( n ) == n - 1 then
if n <= 100 then n100 = n100 + 1 end
if n <= 1000 then n1000 = n1000 + 1 end
if n <= 10000 then n10000 = n10000 + 1 end
if n <= 100000 then n100000 = n100000 + 1 end
end
end
io.write( "There are ", string.format( "%6d", n100 ), " primes below 100\n" )
io.write( "There are ", string.format( "%6d", n1000 ), " primes below 1 000\n" )
io.write( "There are ", string.format( "%6d", n10000 ), " primes below 10 000\n" )
io.write( "There are ", string.format( "%6d", n100000 ), " primes below 100 000\n" )
end
</syntaxhighlight>
{{out}}
<pre>
n phi(n) remarks
1: 1
2: 1 n is prime
3: 2 n is prime
4: 2
5: 4 n is prime
6: 2
7: 6 n is prime
8: 4
9: 6
10: 4
11: 10 n is prime
12: 4
13: 12 n is prime
14: 6
15: 8
16: 8
17: 16 n is prime
18: 6
19: 18 n is prime
20: 8
21: 12
22: 10
23: 22 n is prime
24: 8
25: 20
There are 25 primes below 100
There are 168 primes below 1 000
There are 1229 primes below 10 000
There are 9592 primes below 100 000
</pre>
=={{header|MAD}}==
{{trans|C}}
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER
BOOLEAN PRM
INTERNAL FUNCTION(A,B)
ENTRY TO REM.
FUNCTION RETURN A-A/B*B
END OF FUNCTION
INTERNAL FUNCTION(NN)
ENTRY TO TOTENT.
N = NN
TOT = N
THROUGH STEP, FOR I=2, 2, I*I.G.N
WHENEVER REM.(N,I).E.0
THROUGH DIV, FOR N=N, 0, REM.(N,I).NE.0
DIV N = N/I
TOT = TOT-TOT/I
END OF CONDITIONAL
WHENEVER I.E.2, I=1
STEP CONTINUE
WHENEVER N.G.1, TOT = TOT-TOT/N
FUNCTION RETURN TOT
END OF FUNCTION
COUNT = 0
PRINT FORMAT HEADER
THROUGH FRST25, FOR KN=1, 1, KN.G.25
KTOT = TOTENT.(KN)
PRM = KTOT.E.KN-1
WHENEVER PRM, COUNT = COUNT + 1
FRST25 PRINT FORMAT NUMTOT,KN,KTOT,PRM
PRINT FORMAT NUMPRM,25,COUNT
THROUGH CNTPRM, FOR KN=26, 1, KN.G.100000
KTOT = TOTENT.(KN)
WHENEVER KTOT.E.KN-1, COUNT = COUNT+1
WHENEVER KN.E.100 .OR. KN.E.1000 .OR. REM.(KN,10000).E.0,
0 PRINT FORMAT NUMPRM,KN,COUNT
CNTPRM CONTINUE
VECTOR VALUES HEADER = $19H N TOTIENT PRIME*$
VECTOR VALUES NUMTOT = $I2,S2,I7,S2,I5*$
VECTOR VALUES NUMPRM = $22HNUMBER OF PRIMES UP TO,I7,1H:,I6*$
END OF PROGRAM</syntaxhighlight>
{{out}}
<pre> N TOTIENT PRIME
1 1 0
2 1 1
3 2 1
4 2 0
5 4 1
6 2 0
7 6 1
8 4 0
9 6 0
10 4 0
11 10 1
12 4 0
13 12 1
14 6 0
15 8 0
16 8 0
17 16 1
18 6 0
19 18 1
20 8 0
21 12 0
22 10 0
23 22 1
24 8 0
25 20 0
NUMBER OF PRIMES UP TO 25: 9
NUMBER OF PRIMES UP TO 100: 25
NUMBER OF PRIMES UP TO 1000: 168
NUMBER OF PRIMES UP TO 10000: 1229
NUMBER OF PRIMES UP TO 20000: 2262
NUMBER OF PRIMES UP TO 30000: 3245
NUMBER OF PRIMES UP TO 40000: 4203
NUMBER OF PRIMES UP TO 50000: 5133
NUMBER OF PRIMES UP TO 60000: 6057
NUMBER OF PRIMES UP TO 70000: 6935
NUMBER OF PRIMES UP TO 80000: 7837
NUMBER OF PRIMES UP TO 90000: 8713
NUMBER OF PRIMES UP TO 100000: 9592</pre>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">Do[
tmp = EulerPhi[i];
If[i - 1 == tmp,
Line 1,720 ⟶ 3,646:
(*PrimePi[1000]*)
(*PrimePi[10000]*)
(*PrimePi[100000]*)</
{{out}}
Line 1,754 ⟶ 3,680:
1229
9592</pre>
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (lay (map showline [1..25])),
Stdout (lay (map countprimes (25:map (10^) [2..5])))]
countprimes :: num->[char]
countprimes n = "There are " ++ show amount ++ " primes up to " ++ show n
where amount = #filter prime [2..n]
showline :: num->[char]
showline n = "phi(" ++ show n ++ ") = " ++ show (totient n) ++ ", " ++ kind
where kind = "prime", if prime n
= "composite", otherwise
prime :: num->bool
prime n = totient n = n - 1
totient :: num->num
totient n = loop n n (2:[3, 5..])
where loop tot n (d:ds)
= tot, if n<=1
= tot - tot div n, if d*d > n
= loop tot n ds, if n mod d ~= 0
= loop (tot - tot div d) (remfac n d) ds, otherwise
remfac n d = n, if n mod d ~= 0
= remfac (n div d) d, otherwise</syntaxhighlight>
{{out}}
<pre>phi(1) = 1, composite
phi(2) = 1, prime
phi(3) = 2, prime
phi(4) = 2, composite
phi(5) = 4, prime
phi(6) = 2, composite
phi(7) = 6, prime
phi(8) = 4, composite
phi(9) = 6, composite
phi(10) = 4, composite
phi(11) = 10, prime
phi(12) = 4, composite
phi(13) = 12, prime
phi(14) = 6, composite
phi(15) = 8, composite
phi(16) = 8, composite
phi(17) = 16, prime
phi(18) = 6, composite
phi(19) = 18, prime
phi(20) = 8, composite
phi(21) = 12, composite
phi(22) = 10, composite
phi(23) = 22, prime
phi(24) = 8, composite
phi(25) = 20, composite
There are 9 primes up to 25
There are 25 primes up to 100
There are 168 primes up to 1000
There are 1229 primes up to 10000
There are 9592 primes up to 100000</pre>
=={{header|Modula-2}}==
<syntaxhighlight lang="modula2">MODULE TotientFunction;
FROM InOut IMPORT WriteString, WriteCard, WriteLn;
VAR count, n, tot: CARDINAL;
PROCEDURE totient(n: CARDINAL): CARDINAL;
VAR tot, i: CARDINAL;
BEGIN
tot := n;
i := 2;
WHILE i*i <= n DO
IF n MOD i = 0 THEN
WHILE n MOD i = 0 DO
n := n DIV i
END;
DEC(tot, tot DIV i)
END;
IF i=2 THEN i := 1 END;
INC(i, 2)
END;
IF n>1 THEN
DEC(tot, tot DIV n)
END;
RETURN tot
END totient;
PROCEDURE ShowPrimeCount(n, count: CARDINAL);
BEGIN
WriteString("Number of primes up to");
WriteCard(n, 6);
WriteString(": ");
WriteCard(count, 4);
WriteLn
END ShowPrimeCount;
BEGIN
count := 0;
WriteString(" N Totient Prime");
WriteLn;
FOR n := 1 TO 25 DO
tot := totient(n);
WriteCard(n, 2);
WriteCard(tot, 9);
IF tot = n-1 THEN
WriteString(" Yes");
INC(count)
ELSE
WriteString(" No")
END;
WriteLn
END;
ShowPrimeCount(25, count);
FOR n := 26 TO 10000 DO
IF totient(n) = n-1 THEN INC(count) END;
IF (n=100) OR (n=1000) OR (n=10000) THEN
ShowPrimeCount(n, count)
END;
END
END TotientFunction.</syntaxhighlight>
{{out}}
<pre> N Totient Prime
1 1 No
2 1 Yes
3 2 Yes
4 2 No
5 4 Yes
6 2 No
7 6 Yes
8 4 No
9 6 No
10 4 No
11 10 Yes
12 4 No
13 12 Yes
14 6 No
15 8 No
16 8 No
17 16 Yes
18 6 No
19 18 Yes
20 8 No
21 12 No
22 10 No
23 22 Yes
24 8 No
25 20 No
Number of primes up to 25: 9
Number of primes up to 100: 25
Number of primes up to 1000: 168
Number of primes up to 10000: 1229</pre>
=={{header|Nim}}==
<
func totient(n: int): int =
Line 1,790 ⟶ 3,868:
inc count
if n == 100 or n == 1000 or n mod 10_000 == 0:
echo fmt"Number of primes up to {n:>6} = {count:>4}"</
{{out}}
<pre>
Line 1,838 ⟶ 3,916:
=={{header|Pascal}}==
Yes, a very slow possibility to check prime
<
{$MODE DELPHI}
{$IFEND}
Line 1,902 ⟶ 3,980:
i := i*10;
until i >100000;
end.</
;Output:
<pre>number n Totient(n) isprime
Line 1,941 ⟶ 4,019:
Impressive speedup.Checking with only primes would be even faster.
<
const
//delta of numbers not divisible by 2,3,5 (0_1+6->7+4->11 ..+6->29+2->3_1
Line 2,008 ⟶ 4,086:
if n> 1 then
dec(result,result div n);
end;</
;Output:
<pre>
Line 2,050 ⟶ 4,128:
====Direct calculation of 𝜑====
{{trans|Raku}}
<
binmode STDOUT, ":utf8";
Line 2,072 ⟶ 4,150:
printf "Count of primes <= $limit: %d\n", scalar grep {$_ == $𝜑[$_] + 1} 0..$limit;
}
</syntaxhighlight>
{{out}}
<pre>𝜑( 1) = 1
Line 2,107 ⟶ 4,185:
Much faster. Output is the same as above.
{{libheader|ntheory}}
<
binmode STDOUT, ":utf8";
Line 2,119 ⟶ 4,197:
for $limit (100, 1000, 10000) {
printf "Count of primes <= $limit: %d\n", scalar grep {$_ == $𝜑[$_] + 1} 0..$limit;
}</
=={{header|Phix}}==
{{trans|Go}}
As of 1.0.2 there is a builtin phi().
<!--<syntaxhighlight lang="phix">(phixonline)-->
<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>
<span style="color: #004080;">integer</span> <span style="color: #000000;">tot</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">i</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">2</span>
Line 2,159 ⟶ 4,238:
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</
{{out}}
<pre>
Line 2,196 ⟶ 4,275:
Number of primes up to 100000 = 9592
</pre>
=={{header|PL/I}}==
{{trans|C}}
<syntaxhighlight lang="pli">totientFunction: procedure options(main);
totient: procedure(nn) returns(fixed);
declare (nn, n, i, tot) fixed;
n = nn;
tot = n;
do i=2 repeat(i+2) while(i*i <= n);
if mod(n,i) = 0 then do;
do while(mod(n,i) = 0);
n = n / i;
end;
tot = tot - tot / i;
end;
if i=2 then i=1;
end;
if n>1 then tot = tot - tot/n;
return(tot);
end totient;
showPrimeCount: procedure(n, primeCount);
declare (n, primeCount) fixed;
put skip edit('There are', primeCount, ' primes up to', n) (A,F(5),A,F(6));
end showPrimeCount;
declare (n, primeCount, tot) fixed;
do n = 1 to 25;
tot = totient(n);
put edit('phi(', n, ') = ', tot) (A,F(2),A,F(2));
if tot = n-1 then do;
put list('; prime');
primeCount = primeCount + 1;
end;
put skip;
end;
call showPrimeCount(25, primeCount);
do n = 26 to 10000;
if totient(n) = n-1 then primeCount = primeCount + 1;
if n=100 | n=1000 | n=10000 then
call showPrimeCount(n, primeCount);
end;
end totientFunction;</syntaxhighlight>
{{out}}
<pre>phi( 1) = 1
phi( 2) = 1 ; prime
phi( 3) = 2 ; prime
phi( 4) = 2
phi( 5) = 4 ; prime
phi( 6) = 2
phi( 7) = 6 ; prime
phi( 8) = 4
phi( 9) = 6
phi(10) = 4
phi(11) = 10 ; prime
phi(12) = 4
phi(13) = 12 ; prime
phi(14) = 6
phi(15) = 8
phi(16) = 8
phi(17) = 16 ; prime
phi(18) = 6
phi(19) = 18 ; prime
phi(20) = 8
phi(21) = 12
phi(22) = 10
phi(23) = 22 ; prime
phi(24) = 8
phi(25) = 20
There are 9 primes up to 25
There are 25 primes up to 100
There are 168 primes up to 1000
There are 1229 primes up to 10000</pre>
=={{header|PL/M}}==
{{trans|C}}
<syntaxhighlight lang="plm">100H:
BDOS: PROCEDURE (F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; GO TO 0; END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
PRINT$NUM: PROCEDURE (N);
DECLARE (N, P) ADDRESS, CH BASED P BYTE;
DECLARE S (6) BYTE INITIAL ('.....$');
P = .S(5);
DIGIT:
P = P-1;
CH = '0' + N MOD 10;
IF (N := N/10) > 0 THEN GO TO DIGIT;
CALL PRINT(P);
END PRINT$NUM;
TOTIENT: PROCEDURE (N) ADDRESS;
DECLARE (TOT, N, I) ADDRESS;
TOT = N;
I = 2;
DO WHILE I*I <= N;
IF N MOD I = 0 THEN DO;
DO WHILE (N := N / I) MOD I = 0; END;
TOT = TOT - TOT / I;
END;
IF I=2 THEN I=1;
I = I+2;
END;
IF N > 1 THEN TOT = TOT - TOT / N;
RETURN TOT;
END TOTIENT;
SHOW$PRIME$COUNT: PROCEDURE (N, COUNT);
DECLARE (N, COUNT) ADDRESS;
CALL PRINT(.'THERE ARE $');
CALL PRINT$NUM(COUNT);
CALL PRINT(.' PRIMES UP TO $');
CALL PRINT$NUM(N);
CALL PRINT(.(13,10,'$'));
END SHOW$PRIME$COUNT;
DECLARE (N, TOT) ADDRESS;
DECLARE PRIME$COUNT ADDRESS INITIAL (0);
DO N = 1 TO 25;
CALL PRINT(.'PHI($');
CALL PRINT$NUM(N);
CALL PRINT(.') = $');
CALL PRINT$NUM(TOT := TOTIENT(N));
IF TOT = N-1 THEN DO;
CALL PRINT(.'; PRIME$');
PRIME$COUNT = PRIME$COUNT + 1;
END;
CALL PRINT(.(13,10,'$'));
END;
CALL SHOW$PRIME$COUNT(25, PRIME$COUNT);
DO N = 26 TO 10000;
IF TOTIENT(N) = N-1 THEN
PRIME$COUNT = PRIME$COUNT + 1;
IF N=100 OR N=1000 OR N=10000 THEN
CALL SHOW$PRIME$COUNT(N, PRIME$COUNT);
END;
CALL EXIT;
EOF</syntaxhighlight>
{{out}}
<pre>PHI(1) = 1
PHI(2) = 1; PRIME
PHI(3) = 2; PRIME
PHI(4) = 2
PHI(5) = 4; PRIME
PHI(6) = 2
PHI(7) = 6; PRIME
PHI(8) = 4
PHI(9) = 6
PHI(10) = 4
PHI(11) = 10; PRIME
PHI(12) = 4
PHI(13) = 12; PRIME
PHI(14) = 6
PHI(15) = 8
PHI(16) = 8
PHI(17) = 16; PRIME
PHI(18) = 6
PHI(19) = 18; PRIME
PHI(20) = 8
PHI(21) = 12
PHI(22) = 10
PHI(23) = 22; PRIME
PHI(24) = 8
PHI(25) = 20
THERE ARE 9 PRIMES UP TO 25
THERE ARE 25 PRIMES UP TO 100
THERE ARE 168 PRIMES UP TO 1000
THERE ARE 1229 PRIMES UP TO 10000</pre>
=={{header|PicoLisp}}==
<
(de gcd (A B)
(until (=0 B)
Line 2,225 ⟶ 4,478:
(cdr @) ) ) )
(println
(mapcar p? (25 100 1000 10000 100000)) )</
{{out}}
<pre>
Line 2,258 ⟶ 4,511:
=={{header|Python}}==
<
def φ(n):
Line 2,273 ⟶ 4,526:
count += is_prime(n)
if n in {100, 1000, 10_000}:
print(f"Primes up to {n}: {count}")</
{{out}}
Line 2,307 ⟶ 4,560:
=={{header|Quackery}}==
<code>gcd</code> is defined at [[Greatest common divisor#Quackery]].
<syntaxhighlight lang="quackery "> [ 0 swap dup times
[ i over gcd
1 = rot + swap ]
Line 2,337 ⟶ 4,587:
dup primecount echo
say " primes up to " echo
say "." cr ]</
((Out}}
Line 2,374 ⟶ 4,624:
=={{header|Racket}}==
<
(require math/number-theory)
Line 2,391 ⟶ 4,641:
(when (member n '(100 1000 10000))
(printf "Primes up to ~a: ~a\n" n new-count))
new-count)</
{{out}}
Line 2,430 ⟶ 4,680:
This is an ''incredibly'' inefficient way of finding prime numbers.
<syntaxhighlight lang="raku"
my \𝜑 = 0, |(1..*).hyper.map: -> \t { t * [*] t.&prime-factors.squish.map: { 1 - 1/$_ } }
Line 2,438 ⟶ 4,688:
(1e2, 1e3, 1e4, 1e5).map: -> $limit {
say "\nCount of primes <= $limit: " ~ +(^$limit).grep: {$_ == 𝜑[$_] + 1}
}</
{{out}}
<pre>𝜑( 1) = 1
Line 2,476 ⟶ 4,726:
=={{header|REXX}}==
=== idiomatic ===
<
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 25 /*Not specified? Then use the default.*/
Line 2,499 ⟶ 4,749:
#= 1
do m=2 for z-2; if gcd(m, z)==1 then #= # + 1
end /*m*/; return #</
{{out|output|text= when using the default input of: <tt> 25 </tt>}}
<pre>
Line 2,550 ⟶ 4,800:
This REXX version moved the '''gcd''' function in-line.
<br>It is about '''7%''' faster than the 1<sup>st</sup> version.
<
parse arg N . /*obtain optional argument from the CL.*/
if N=='' | N=="," then N= 25 /*Not specified? Then use the default.*/
Line 2,574 ⟶ 4,824:
if x==1 then #= # + 1
end /*m*/
return #</
{{out|output|text= is identical to the 1<sup>st</sup> REXX version.}} <br><br>
=={{header|RPL}}==
===GCD approach===
Very compact code, but very slow algorithm.
≪ → n
≪ 0 1 n FOR j
n j
WHILE DUP REPEAT SWAP OVER MOD END
DROP 1 == +
NEXT
≫ ≫
‘PHI’ STO
≪ 1 1 ROT FOR j
j DUP PHI - 1 == +
2 STEP
≫
'CNTPR' STO
25 PHI
10000 CNTPR
{{out}}
<pre>
2: 20
1: 1229
</pre>
===Faster version===
{{trans|C}}
Calculator simulator's timedog unfortunately prevents from running the code to count up to 100,000.
{{works with|Halcyon Calc|4.2.7}}
≪ DUP 2 OVER √
FOR j
IF DUP j MOD NOT THEN
WHILE DUP j MOD NOT REPEAT
j /
END
SWAP DUP j / - SWAP
END
IF j 2 == THEN 1 'j' STO END
2 STEP
IF DUP 1 > THEN OVER SWAP / - ELSE DROP END
≫
‘PHI’ STO
=={{header|Ruby}}==
<
require "prime"
def 𝜑(n)
n.prime_division.inject(1)
end
Line 2,593 ⟶ 4,886:
puts "Number of primes up to #{u}: #{(1..u).count{|n| n-𝜑(n) == 1} }"
end
</syntaxhighlight>
{{out}}
<pre>
Line 2,629 ⟶ 4,922:
=={{header|Rust}}==
<
fn main() {
Line 2,655 ⟶ 4,948:
fn phi(n: usize) -> usize {
(1..=n).filter(|&x| gcd(n, x) == 1).count()
}</
Output is:
Line 2,691 ⟶ 4,984:
</pre>
=={{header|S-BASIC}}==
<syntaxhighlight lang="basic">
$lines
rem - return p mod q
function mod(p, q = integer) = integer
end = p - q * (p / q)
rem - return greatest common divisor of x and y
function gcd(x, y = integer) = integer
var r, temp = integer
if x < y then
begin
temp = x
x = y
y = temp
end
r = mod(x, y)
while r <> 0 do
begin
x = y
y = r
r = mod(x, y)
end
end = y
rem - return phi (also called totient) of n
function phi(n = integer) = integer
var i, count = integer
count = 1
for i = 2 to n
if gcd(n, i) = 1 then count = count + 1
next i
end = count
rem - exercise the function
var n, totient, count = integer
print " n Phi(n) Prime?"
for n = 1 to 25
totient = phi(n)
print using "#### #### ";n, totient;
if totient + 1 = n then
print "yes"
else
print "no"
next n
rem - and further test it by counting primes
print
count = 0
for n = 1 to 1000
if phi(n) = n - 1 then count = count + 1
if n = 100 then
print "Primes up to 100 = ";count
else if n = 1000 then
print "Primes up to 1000 = ";count
next n
end
</syntaxhighlight>
{{out}}
<pre>
n Phi(n) Prime?
1 1 no
2 1 yes
3 2 yes
4 2 no
5 4 yes
6 2 no
7 6 yes
8 4 no
9 6 no
10 4 no
11 10 yes
12 4 no
13 12 yes
14 6 no
15 8 no
16 8 no
17 16 yes
18 6 no
19 18 yes
20 8 no
21 12 no
22 10 no
23 22 yes
24 8 no
25 20 no
Primes up to 100 = 25
Primes up to 1000 = 168
</pre>
=={{header|Scala}}==
The most concise way to write the totient function in Scala is using a naive lazy list:
<
def gcd(a: Int, b: Int): Int = if(b == 0) a else gcd(b, a%b)
def totientLaz(num: Int): Int = LazyList.range(2, num).count(gcd(num, _) == 1) + 1</
The above approach, while concise, is not very performant. It must check the GCD with every number between 2 and num, giving it an O(n*log(n)) time complexity. A better solution is to use the product definition of the totient, repeatedly extracting prime factors from num:
<
@tailrec
def dTrec(f: Int, n: Int): Int = if(n%f == 0) dTrec(f, n/f) else n
Line 2,712 ⟶ 5,097:
tTrec(num, 2, num)
}</
This version is significantly faster, but the introduction of multiple recursive methods makes it far less concise. We can, however, embed the recursion into a lazy list to obtain a function as fast as the second example yet almost as concise as the first, at the cost of some readability:
<
def scrub(f: Long, num: Long): Long = if(num%f == 0) scrub(f, num/f) else num
def totientLazPrd(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)}.find(_._3 == 1).get._1</
To generate the output up to 100000, Longs are necessary.
Line 2,752 ⟶ 5,137:
10000: 1229
100000: 9592</pre>
=={{header|SETL}}==
<syntaxhighlight lang="setl">program totient;
loop for n in [1..1000000] do
tot := totient(n);
if tot = n-1 then prime +:= 1; end if;
if n <= 25 then
print(lpad(str n, 2), " ",
lpad(str tot, 2), " ",
if tot = n-1 then "prime" else "" end if);
end if;
if n in [1000,10000,100000,1000000] then
print(lpad(str prime,8), "primes up to" + lpad(str n,8));
end if;
end loop;
proc totient(n);
tot := n;
i := 2;
loop while i*i <= n do
if n mod i = 0 then
loop while n mod i = 0 do
n div:= i;
end loop;
tot -:= tot div i;
end if;
if i=2 then i:=3;
else i+:=2;
end if;
end loop;
if n>1 then
tot -:= tot div n;
end if;
return tot;
end proc;
end program;</syntaxhighlight>
{{out}}
<pre> 1 1
2 1 prime
3 2 prime
4 2
5 4 prime
6 2
7 6 prime
8 4
9 6
10 4
11 10 prime
12 4
13 12 prime
14 6
15 8
16 8
17 16 prime
18 6
19 18 prime
20 8
21 12
22 10
23 22 prime
24 8
25 20
168 primes up to 1000
1229 primes up to 10000
9592 primes up to 100000
78498 primes up to 1000000</pre>
=={{header|Shale}}==
Line 2,843 ⟶ 5,296:
=={{header|Sidef}}==
The Euler totient function is built-in as '''Number.euler_phi()''', but we can easily re-implement it using its multiplicative property: '''phi(p^k) = (p-1)*p^(k-1)'''.
<
n.factor_exp.prod {|p|
(p[0]-1) * p[0]**(p[1]-1)
}
}</
<
var totient = 𝜑(n)
printf("𝜑(%2s) = %3s%s\n", n, totient, totient==(n-1) ? ' - prime' : '')
}</
{{out}}
<pre style="height:35ex">
Line 2,882 ⟶ 5,335:
</pre>
<
var pi = (1..limit -> count_by {|n| 𝜑(n) == (n-1) })
say "Number of primes <= #{limit}: #{pi}"
}</
{{out}}
<pre>
Line 2,896 ⟶ 5,349:
=={{header|Tiny BASIC}}==
1 indicates prime, 0 indicates not prime.
<
LET N = 0
10 LET N = N + 1
Line 2,934 ⟶ 5,387:
LET A = B
LET B = S
GOTO 2010</
{{out}}<pre>1 1 0
2 1 1
Line 2,965 ⟶ 5,418:
=={{header|VBA}}==
{{trans|Phix}}<
Dim tot As Long: tot = n
Dim i As Long: i = 2
Line 3,005 ⟶ 5,458:
End Select
Next n
End Sub</
<pre> n phi prime
--------------
Line 3,042 ⟶ 5,495:
=={{header|Visual Basic .NET}}==
{{trans|C#}}
<
Module Module1
Line 3,095 ⟶ 5,548:
End Function
End Module</
{{out}}
<pre>1 1
Line 3,131 ⟶ 5,584:
{{trans|Go}}
{{libheader|Wren-fmt}}
<
var totient = Fn.new { |n|
Line 3,164 ⟶ 5,617:
System.print("\nNumber of primes up to %(Fmt.d(-6, n)) = %(count)")
}
}</
{{out}}
Line 3,221 ⟶ 5,674:
Number of primes up to 100000 = 9592
</pre>
=={{header|XPL0}}==
<syntaxhighlight lang="xpl0">func GCD(N, D); \Return the greatest common divisor of N and D
int N, D; \numerator and denominator
int R;
[if D > N then
[R:= D; D:= N; N:= R]; \swap D and N
while D > 0 do
[R:= rem(N/D);
N:= D;
D:= R;
];
return N;
]; \GCD
func Totient(N); \Return the totient of N
int N, Phi, M;
[Phi:= 0;
for M:= 1 to N do
if GCD(M, N) = 1 then Phi:= Phi+1;
return Phi;
];
int N, Phi, Pwr, C, Limit;
[Text(0, "n phi is prime^m^j");
for N:= 1 to 25 do
[IntOut(0, N); ChOut(0, 9\tab\);
Phi:= Totient(N);
IntOut(0, Phi); ChOut(0, 9\tab\);
Text(0, if Phi = N-1 then "true" else "false");
CrLf(0);
];
CrLf(0);
for Pwr:= 2 to 4 do
[C:= 0;
Limit:= fix(Pow(10.0, float(Pwr)));
IntOut(0, Limit); ChOut(0, 9\tab\);
for N:= 1 to Limit do
[Phi:= Totient(N);
if Phi = N-1 then C:= C+1;
];
IntOut(0, C); CrLf(0);
];
]</syntaxhighlight>
{{out}}
<pre>
n phi is prime
1 1 false
2 1 true
3 2 true
4 2 false
5 4 true
6 2 false
7 6 true
8 4 false
9 6 false
10 4 false
11 10 true
12 4 false
13 12 true
14 6 false
15 8 false
16 8 false
17 16 true
18 6 false
19 18 true
20 8 false
21 12 false
22 10 false
23 22 true
24 8 false
25 20 false
100 25
1000 168
10000 1229
</pre>
=={{header|zkl}}==
<
fcn isPrime(n){ totient(n)==(n - 1) }</
<
println("\u03c6(%2d) ==%3d %s"
.fmt(n,totient(n),isPrime(n) and "is prime" or ""));
}</
{{out}}
<pre style="height:35ex">
Line 3,258 ⟶ 5,789:
φ(25) == 20
</pre>
<
foreach n in ([1..10_000]){ // yes, this is sloooow
count+=isPrime(n);
if(n==100 or n==1000 or n==10_000)
println("Primes <= %,6d : %,5d".fmt(n,count));
}</
{{out}}
<pre>
|