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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Amicable pairs step by step in the Zig 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 Zig programming language

Source code in the zig programming language

const MAXIMUM: u32 = 20_000;

// Fill up a given array with arr[n] = sum(propDivs(n))
pub fn calcPropDivs(divs: []u32) void {
    for (divs) |*d| d.* = 1;
    var i: u32 = 2;
    while (i <= divs.len/2) : (i += 1) {
        var j = i * 2;
        while (j < divs.len) : (j += i)
            divs[j] += i;
    }
}

// Are (A, B) an amicable pair?
pub fn amicable(divs: []const u32, a: u32, b: u32) bool {
    return divs[a] == b and a == divs[b];
}

pub fn main() !void {
    const stdout = @import("std").io.getStdOut().writer();

    var divs: [MAXIMUM + 1]u32 = undefined;
    calcPropDivs(divs[0..]);
    
    var a: u32 = 1;
    while (a < divs.len) : (a += 1) {
        var b = a+1;
        while (b < divs.len) : (b += 1) {
            if (amicable(divs[0..], a, b))
                try stdout.print("{d}, {d}\n", .{a, b});
        }
    }
}


  

You may also check:How to resolve the algorithm Literals/String step by step in the Liberty BASIC programming language
You may also check:How to resolve the algorithm Palindrome detection step by step in the Prolog programming language
You may also check:How to resolve the algorithm Character codes step by step in the ACL2 programming language
You may also check:How to resolve the algorithm Factors of an integer step by step in the PowerShell programming language
You may also check:How to resolve the algorithm Active Directory/Connect step by step in the PicoLisp programming language