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

Published on 12 May 2024 09:40 PM

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

Source code in the elixir programming language

defmodule Proper do
  def divisors(1), do: []
  def divisors(n), do: [1 | divisors(2,n,:math.sqrt(n))] |> Enum.sort
  
  defp divisors(k,_n,q) when k>q, do: []
  defp divisors(k,n,q) when rem(n,k)>0, do: divisors(k+1,n,q)
  defp divisors(k,n,q) when k * k == n, do: [k | divisors(k+1,n,q)]
  defp divisors(k,n,q)                , do: [k,div(n,k) | divisors(k+1,n,q)]
end

map = Map.new(1..20000, fn n -> {n, Proper.divisors(n) |> Enum.sum} end)
Enum.filter(map, fn {n,sum} -> map[sum] == n and n < sum end)
|> Enum.sort
|> Enum.each(fn {i,j} -> IO.puts "#{i} and #{j}" end)


  

You may also check:How to resolve the algorithm Hello world/Text step by step in the Fexl programming language
You may also check:How to resolve the algorithm Greatest common divisor step by step in the ATS programming language
You may also check:How to resolve the algorithm Literals/Floating point step by step in the EasyLang programming language
You may also check:How to resolve the algorithm Number reversal game step by step in the Clojure programming language
You may also check:How to resolve the algorithm Rosetta Code/Find bare lang tags step by step in the Raku programming language