How to resolve the algorithm Amicable pairs step by step in the Tcl programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Amicable pairs step by step in the Tcl 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 Tcl programming language
Source code in the tcl programming language
proc properDivisors {n} {
if {$n == 1} return
set divs 1
set sum 1
for {set i 2} {$i*$i <= $n} {incr i} {
if {!($n % $i)} {
lappend divs $i
incr sum $i
if {$i*$i < $n} {
lappend divs [set d [expr {$n / $i}]]
incr sum $d
}
}
}
return [list $sum $divs]
}
proc amicablePairs {limit} {
set result {}
set sums [set divs {{}}]
for {set n 1} {$n < $limit} {incr n} {
lassign [properDivisors $n] sum d
lappend sums $sum
lappend divs [lsort -integer $d]
}
for {set n 1} {$n < $limit} {incr n} {
set nsum [lindex $sums $n]
for {set m 1} {$m < $n} {incr m} {
if {$n==[lindex $sums $m] && $m==$nsum} {
lappend result $m $n [lindex $divs $m] [lindex $divs $n]
}
}
}
return $result
}
foreach {m n md nd} [amicablePairs 20000] {
puts "$m and $n are an amicable pair with these proper divisors"
puts "\t$m : $md"
puts "\t$n : $nd"
}
You may also check:How to resolve the algorithm Amicable pairs step by step in the MiniScript programming language
You may also check:How to resolve the algorithm URL parser step by step in the F# programming language
You may also check:How to resolve the algorithm Matrix transposition step by step in the Euphoria programming language
You may also check:How to resolve the algorithm Loops/Infinite step by step in the XPL0 programming language
You may also check:How to resolve the algorithm Arithmetic-geometric mean/Calculate Pi step by step in the Perl programming language