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

Published on 12 May 2024 09:40 PM

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

Source code in the rust programming language

fn sum_of_divisors(val: u32) -> u32 {
    (1..val/2+1).filter(|n| val % n == 0)
                .fold(0, |sum, n| sum + n)
}

fn main() {
    let iter = (1..20_000).map(|i| (i, sum_of_divisors(i)))
                          .filter(|&(i, div_sum)| i > div_sum);

    for (i, sum1) in iter {
        if sum_of_divisors(sum1) == i {
           println!("{} {}", i, sum1);
        }
    }
}


fn main() {
    const RANGE_MAX: u32 = 20_000;
    
    let proper_divs = |n: u32| -> Vec<u32> {
        (1..=(n + 1) / 2).filter(|&x| n % x == 0).collect()
    };
    
    let n2d: Vec<u32> = (1..=RANGE_MAX).map(|n| proper_divs(n).iter().sum()).collect();
    
    for (n, &div_sum) in n2d.iter().enumerate() {
        let n = n as u32 + 1;
        
        if n < div_sum && div_sum <= RANGE_MAX && n2d[div_sum as usize - 1] == n {
            println!("Amicable pair: {} and {} with proper divisors:", n, div_sum);
            println!("    {:?}", proper_divs(n));
            println!("    {:?}", proper_divs(div_sum));
        }
    }
}


  

You may also check:How to resolve the algorithm Respond to an unknown method call step by step in the Icon and Unicon programming language
You may also check:How to resolve the algorithm Real constants and functions step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm 24 game/Solve step by step in the Simula programming language
You may also check:How to resolve the algorithm Bitmap/Midpoint circle algorithm step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Partition an integer x into n primes step by step in the Swift programming language