How to resolve the algorithm Almost prime step by step in the D programming language

Published on 12 May 2024 09:40 PM
#D

How to resolve the algorithm Almost prime step by step in the D programming language

Table of Contents

Problem Statement

A   k-Almost-prime   is a natural number

n

{\displaystyle n}

that is the product of

k

{\displaystyle k}

(possibly identical) primes.

1-almost-primes,   where

k

1

{\displaystyle k=1}

,   are the prime numbers themselves. 2-almost-primes,   where

k

2

{\displaystyle k=2}

,   are the   semiprimes.

Write a function/method/subroutine/... that generates k-almost primes and use it to create a table here of the first ten members of k-Almost primes for

1 <= K <= 5

{\displaystyle 1<=K<=5}

.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Almost prime step by step in the D programming language

Source code in the d programming language

import std.stdio, std.algorithm, std.traits;

Unqual!T[] decompose(T)(in T number) pure nothrow
in {
    assert(number > 1);
} body {
    typeof(return) result;
    Unqual!T n = number;

    for (Unqual!T i = 2; n % i == 0; n /= i)
        result ~= i;
    for (Unqual!T i = 3; n >= i * i; i += 2)
        for (; n % i == 0; n /= i)
            result ~= i;

    if (n != 1)
        result ~= n;
    return result;
}

void main() {
    enum outLength = 10; // 10 k-th almost primes.

    foreach (immutable k; 1 .. 6) {
        writef("K = %d: ", k);
        auto n = 2; // The "current number" to be checked.
        foreach (immutable i; 1 .. outLength + 1) {
            while (n.decompose.length != k)
                n++;
            // Now n is K-th almost prime.
            write(n, " ");
            n++;
        }
        writeln;
    }
}


  

You may also check:How to resolve the algorithm Read a file line by line step by step in the Scheme programming language
You may also check:How to resolve the algorithm Nth root step by step in the Objeck programming language
You may also check:How to resolve the algorithm Nth root step by step in the Wren programming language
You may also check:How to resolve the algorithm Variables step by step in the JavaScript programming language
You may also check:How to resolve the algorithm Nonogram solver step by step in the D programming language