Generate and show here, the first twenty Perfect totient numbers.



Related task

   Totient function


Also see

   the OEIS entry for   perfect totient numbers.
   mrob   list of the first 54


MODULE PerfectTotient;
FROM InOut IMPORT WriteCard, WriteLn;
 
CONST Amount = 20;
VAR n, seen: CARDINAL;
 
PROCEDURE GCD(a, b: CARDINAL): CARDINAL;
VAR c: CARDINAL;
BEGIN
    WHILE b # 0 DO
        c := a MOD b;
        a := b;
        b := c;
    END;
    RETURN a;
END GCD;
 
PROCEDURE Totient(n: CARDINAL): CARDINAL;
VAR i, tot: CARDINAL;
BEGIN
    tot := 0;
    FOR i := 1 TO n/2 DO
        IF GCD(n,i) = 1 THEN
            tot := tot + 1;
        END;
    END;
    RETURN tot;
END Totient;
 
PROCEDURE Perfect(n: CARDINAL): BOOLEAN;
VAR sum, x: CARDINAL;
BEGIN
    sum := 0;
    x := n;
    REPEAT
        x := Totient(x);
        sum := sum + x;
    UNTIL x = 1;
    RETURN sum = n;
END Perfect;
 
BEGIN
    seen := 0;
    n := 3;
    WHILE seen < Amount DO
        IF Perfect(n) THEN
            WriteCard(n,5);
            seen := seen + 1;
            IF seen MOD 14 = 0 THEN
                WriteLn();
            END;
        END;
        n := n + 2;
    END;
    WriteLn();
END PerfectTotient.