How to resolve the algorithm Amicable pairs step by step in the D programming language

Published on 12 May 2024 09:40 PM
#D

How to resolve the algorithm Amicable pairs step by step in the D programming language

Table of Contents

Problem Statement

Two integers

N

{\displaystyle N}

and

M

{\displaystyle M}

are said to be amicable pairs if

N ≠ M

{\displaystyle N\neq M}

and the sum of the proper divisors of

N

{\displaystyle N}

(

s u m

(

p r o p D i v s

( N ) )

{\displaystyle \mathrm {sum} (\mathrm {propDivs} (N))}

)

= M

{\displaystyle =M}

as well as

s u m

(

p r o p D i v s

( M ) )

N

{\displaystyle \mathrm {sum} (\mathrm {propDivs} (M))=N}

.

1184 and 1210 are an amicable pair, with proper divisors:

Calculate and show here the Amicable pairs below 20,000; (there are eight).

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Amicable pairs step by step in the D programming language

Source code in the d programming language

void main() @safe /*@nogc*/ {
    import std.stdio, std.algorithm, std.range, std.typecons, std.array;

    immutable properDivs = (in uint n) pure nothrow @safe /*@nogc*/ =>
        iota(1, (n + 1) / 2 + 1).filter!(x => n % x == 0);

    enum rangeMax = 20_000;
    auto n2d = iota(1, rangeMax + 1).map!(n => properDivs(n).sum);

    foreach (immutable n, immutable divSum; n2d.enumerate(1))
        if (n < divSum && divSum <= rangeMax && n2d[divSum - 1] == n)
            writefln("Amicable pair: %d and %d with proper divisors:\n    %s\n    %s",
                     n, divSum, properDivs(n), properDivs(divSum));
}


  

You may also check:How to resolve the algorithm Angles (geometric), normalization and conversion step by step in the AWK programming language
You may also check:How to resolve the algorithm Averages/Mean angle step by step in the IDL programming language
You may also check:How to resolve the algorithm Twin primes step by step in the C# programming language
You may also check:How to resolve the algorithm Determine if a string is numeric step by step in the ActionScript programming language
You may also check:How to resolve the algorithm Ascending primes step by step in the FreeBASIC programming language