How to resolve the algorithm Totient function step by step in the D programming language

Published on 12 May 2024 09:40 PM
#D

How to resolve the algorithm Totient function step by step in the D programming language

Table of Contents

Problem Statement

The   totient   function is also known as:

The totient function:

If the totient number   (for N)   is one less than   N,   then   N   is prime.

Create a   totient   function and: Show all output here.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Totient function step by step in the D programming language

Source code in the d programming language

import std.stdio;

int totient(int n) {
    int tot = n;

    for (int i = 2; i * i <= n; i += 2) {
        if (n % i == 0) {
            while (n % i == 0) {
                n /= i;
            }
            tot -= tot / i;
        }
        if (i==2) {
            i = 1;
        }
    }

    if (n > 1) {
        tot -= tot / n;
    }
    return tot;
}

void main() {
    writeln(" n    φ   prime");
    writeln("---------------");

    int count = 0;
    for (int n = 1; n <= 25; n++) {
        int tot = totient(n);

        if (n - 1 == tot) {
            count++;
        }

        writefln("%2d   %2d   %s", n,tot, n - 1 == tot);
    }
    writeln;

    writefln("Number of primes up to %6d = %4d", 25, count);
    for (int n = 26; n <= 100_000; n++) {
        int tot = totient(n);

        if (n - 1 == tot) {
            count++;
        }

        if (n == 100 || n == 1_000 || n % 10_000 == 0) {
            writefln("Number of primes up to %6d = %4d", n, count);
        }
    }
}


  

You may also check:How to resolve the algorithm Use another language to call a function step by step in the TXR programming language
You may also check:How to resolve the algorithm Execute a system command step by step in the Perl programming language
You may also check:How to resolve the algorithm Sequence of primorial primes step by step in the Raku programming language
You may also check:How to resolve the algorithm Documentation step by step in the Ada programming language
You may also check:How to resolve the algorithm Repeat a string step by step in the LFE programming language