Amicable pairs: Difference between revisions

m
syntax highlighting fixup automation
m (syntax highlighting fixup automation)
Line 21:
 
=={{header|11l}}==
<langsyntaxhighlight lang=11l>F sum_proper_divisors(n)
R I n < 2 {0} E sum((1 .. n I/ 2).filter(it -> (@n % it) == 0))
 
Line 27:
V m = sum_proper_divisors(n)
I m > n & sum_proper_divisors(m) == n
print(n"\t"m)</langsyntaxhighlight>
 
=={{header|8080 Assembly}}==
<langsyntaxhighlight lang=8080asm> org 100h
;;; Calculate proper divisors of 2..20000
lxi h,pdiv + 4 ; 2 bytes per entry
Line 151:
nbuf: db ' $'
nl: db 13,10,'$'
pdiv: equ $ ; base</langsyntaxhighlight>
{{out}}
<pre>220 284
Line 163:
 
=={{header|8086 Assembly}}==
<langsyntaxhighlight lang=asm>LIMIT: equ 20000 ; Maximum value
cpu 8086
org 100h
Line 252:
nbuf: db ' $'
nl: db 13,10,'$'
final: equ $</langsyntaxhighlight>
{{out}}
<pre>220 284
Line 264:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<langsyntaxhighlight lang=AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program amicable64.s */
Line 427:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
</lang>
<pre>
220 : 284
Line 442:
Calculations on a real Atari 8-bit computer take quite long time. It is recommended to use an emulator capable with increasing speed of Atari CPU.
{{libheader|Action! Sieve of Eratosthenes}}
<langsyntaxhighlight lang=Action!>INCLUDE "H6:SIEVE.ACT"
 
CARD FUNC SumDivisors(CARD x)
Line 480:
FI
OD
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Amicable_pairs.png Screenshot from Atari 8-bit computer]
Line 499:
[[http://rosettacode.org/wiki/Proper_divisors#Ada]].
 
<langsyntaxhighlight lang=Ada>with Ada.Text_IO, Generic_Divisors; use Ada.Text_IO;
procedure Amicable_Pairs is
Line 518:
end if;
end loop;
end Amicable_Pairs;</langsyntaxhighlight>
{{Out}}
<pre>
Line 533:
=={{header|ALGOL 60}}==
{{works with|A60}}
<langsyntaxhighlight lang=algol60>
begin
 
Line 585:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 601:
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang=algol68># returns the sum of the proper divisors of n #
# if n = 1, 0 or -1, we return 0 #
PROC sum proper divisors = ( INT n )INT:
Line 643:
FI
OD
OD</langsyntaxhighlight>
{{out}}
<pre>
Line 660:
{{Trans|GFA Basic}}
 
<langsyntaxhighlight lang=ANSI Standard BASIC>100 DECLARE EXTERNAL FUNCTION sum_proper_divisors
110 CLEAR
120 !
Line 698:
460 END IF
470 LET sum_proper_divisors = sum
480 END FUNCTION</langsyntaxhighlight>
 
=={{header|AppleScript}}==
Line 704:
{{Trans|JavaScript}}
 
<langsyntaxhighlight lang=AppleScript>-- AMICABLE PAIRS ------------------------------------------------------------
 
-- amicablePairsUpTo :: Int -> Int
Line 846:
end script
end if
end mReturn</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight lang=AppleScript>{{220, 284}, {1184, 1210}, {2620, 2924}, {5020, 5564},
{6232, 6368}, {10744, 10856}, {12285, 14595}, {17296, 18416}}</langsyntaxhighlight>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<langsyntaxhighlight lang=ARM Assembly>
/* ARM assembly Raspberry PI or android with termux */
/* program amicable.s */
Line 1,004:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
</lang>
<pre>
220 : 284
Line 1,016:
</pre>
=={{header|Arturo}}==
<langsyntaxhighlight lang=rebol>properDivs: function [x] ->
(factors x) -- x
 
Line 1,035:
]
 
print unique amicables</langsyntaxhighlight>
 
{{out}}
Line 1,042:
 
=={{header|ATS}}==
<langsyntaxhighlight lang=ATS>
(* ****** ****** *)
//
Line 1,147:
 
(* ****** ****** *)
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,162:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight lang=d>SetBatchLines -1
Loop, 20000
{
Line 1,214:
}
MsgBox % final
ExitApp</langsyntaxhighlight>
{{out}}
<pre>
Line 1,228:
 
=={{header|AWK}}==
<langsyntaxhighlight lang=awk>
#!/bin/awk -f
function sumprop(num, i,sum,root) {
Line 1,256:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,274:
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang=BASIC256>function SumProperDivisors(number)
if number < 2 then return 0
sum = 0
Line 1,298:
end if
next n
end</langsyntaxhighlight>
{{out}}
<pre>The pairs of amicable numbers below 20,000 are :
Line 1,313:
 
=={{header|BCPL}}==
<langsyntaxhighlight lang=bcpl>get "libhdr"
 
manifest $(
Line 1,342:
if amicable(pds, x, y) do
writef("%N, %N*N", x, y)
$)</langsyntaxhighlight>
 
{{out}}
Line 1,356:
=={{header|Befunge}}==
 
<langsyntaxhighlight lang=befunge>v_@#-*8*:"2":$_:#!2#*8#g*#6:#0*#!:#-*#<v>*/.55+,
1>$$:28*:*:*%\28*:*:*/`06p28*:*:*/\2v %%^:*:<>*v
+|!:-1g60/*:*:*82::+**:*:<<>:#**#8:#<*^>.28*^8 :
:v>>*:*%/\28*:*:*%+\v>8+#$^#_+#`\:#0<:\`1/*:*2#<
2v^:*82\/*:*:*82:::_v#!%%*:*:*82\/*:*:*82::<_^#<
>>06p:28*:*:**1+01-\>1+::28*:*:*/\28*:*:*%:*\`!^</langsyntaxhighlight>
 
{{out}}
Line 1,378:
 
The program will overflow and error in all sorts of ways when given a commandline argument >= UINT_MAX/2 (generally 2^31)
<langsyntaxhighlight lang=c>#include <stdio.h>
#include <stdlib.h>
 
Line 1,433:
printf("\nTop %u count : %u\n",top,cnt);
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,462:
 
=={{header|C sharp|C#}}==
<langsyntaxhighlight lang=csharp>using System;
using System.Collections.Generic;
using System.Linq;
Line 1,498:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,512:
 
=={{header|C++}}==
<langsyntaxhighlight lang=cpp>
#include <vector>
#include <unordered_map>
Line 1,561:
std::cout << count << " amicable pairs discovered" << std::endl;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,576:
 
=={{header|Clojure}}==
<langsyntaxhighlight lang=lisp>
(ns example
(:gen-class))
Line 1,600:
(doseq [q find-pairs]
(println q))
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,614:
 
=={{header|CLU}}==
<langsyntaxhighlight lang=clu>% Generate proper divisors from 1 to max
proper_divisors = proc (max: int) returns (array[int])
divs: array[int] := array[int]$fill(1, max, 0)
Line 1,643:
end
end
end start_up</langsyntaxhighlight>
{{out}}
<pre>220, 284
Line 1,655:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang=lisp>(let ((cache (make-hash-table)))
(defun sum-proper-divisors (n)
(or (gethash n cache)
Line 1,669:
collect (list x sum-divs)))
 
(amicable-pairs-up-to 20000)</langsyntaxhighlight>
{{out}}
<pre>((220 284) (1184 1210) (2620 2924) (5020 5564) (6232 6368) (10744 10856)
Line 1,675:
 
=={{header|Cowgol}}==
<langsyntaxhighlight lang=cowgol>include "cowgol.coh";
 
const LIMIT := 20000;
Line 1,714:
end loop;
i := i + 1;
end loop;</langsyntaxhighlight>
{{out}}
<pre>220, 284
Line 1,726:
 
=={{header|Crystal}}==
<langsyntaxhighlight lang=Crystal>
MX = 524_000_000
N = Math.sqrt(MX).to_u32
Line 1,747:
end
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,767:
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang=d>void main() @safe /*@nogc*/ {
import std.stdio, std.algorithm, std.range, std.typecons, std.array;
 
Line 1,780:
writefln("Amicable pair: %d and %d with proper divisors:\n %s\n %s",
n, divSum, properDivs(n), properDivs(divSum));
}</langsyntaxhighlight>
{{out}}
<pre>Amicable pair: 220 and 284 with proper divisors:
Line 1,811:
 
=={{header|Draco}}==
<langsyntaxhighlight lang=draco>/* Fill a given array such that for each N,
* P[n] is the sum of proper divisors of N */
proc nonrec propdivs([*] word p) void:
Line 1,838:
od
od
corp</langsyntaxhighlight>
{{out}}
<pre> 220, 284
Line 1,850:
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang=scheme>
;; using (sum-divisors) from math.lib
 
Line 1,869:
→ (... (802725 . 863835) (879712 . 901424) (898216 . 980984) (947835 . 1125765) (998104 . 1043096))
 
</syntaxhighlight>
</lang>
 
=={{header|Ela}}==
{{trans|Haskell}}
<langsyntaxhighlight lang=ela>open monad io number list
 
divisors n = filter ((0 ==) << (n `mod`)) [1..(n `div` 2)]
Line 1,880:
pairs = [(n, m) \\ (n, nd) <- divs, (m, md) <- divs | n < m && nd == m && md == n]
 
do putLn pairs ::: IO</langsyntaxhighlight>
 
{{out}}
Line 1,889:
{{trans|C#}}
ELENA 5.0 :
<langsyntaxhighlight lang=elena>import extensions;
import system'routines;
Line 1,924:
console.printLine(pair.Item1, " ", pair.Item2)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,937:
</pre>
=== Alternative variant using strong-typed closures ===
<langsyntaxhighlight lang=elena>import extensions;
import system'routines'stex;
import system'collections;
Line 1,970:
console.printLine(pair.Item1, " ", pair.Item2)
}
}</langsyntaxhighlight>
=== Alternative variant using yield enumerator ===
<langsyntaxhighlight lang=elena>import extensions;
import system'routines'stex;
import system'collections;
Line 2,016:
console.printLine(pair.Item1, " ", pair.Item2)
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,032:
{{works with|Elixir|1.2}}
With [[proper_divisors#Elixir]] in place:
<langsyntaxhighlight lang=elixir>defmodule Proper do
def divisors(1), do: []
def divisors(n), do: [1 | divisors(2,n,:math.sqrt(n))] |> Enum.sort
Line 2,045:
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)</langsyntaxhighlight>
 
{{out}}
Line 2,063:
Very slow solution. Same functions by and large as in proper divisors and co.
 
<langsyntaxhighlight lang=erlang>
-module(properdivs).
-export([amicable/1,divs/1,sumdivs/1]).
Line 2,099:
sumdivs(N) -> lists:sum(divs(N)).
</langsyntaxhighlight>
{{out}}
<pre>
Line 2,135:
[See the talk section &nbsp; '''amicable pairs, out of order''' &nbsp; for this Rosetta Code task.]
 
<langsyntaxhighlight lang=erlang>
friendly(Limit) ->
List = [{X,properdivs:sumdivs(X)} || X <- lists:seq(3,Limit)],
Line 2,144:
io:format("L: ~w~n", [Final]).
 
</syntaxhighlight>
</lang>
{{output}}
 
Line 2,154:
 
We might answer a challenge by saying:
<langsyntaxhighlight lang=erlang>
friendly(Limit) ->
List = [{X,properdivs:sumdivs(X)} || X <- lists:seq(3,Limit)],
Line 2,175:
end.
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,192:
 
=={{header|ERRE}}==
<langsyntaxhighlight lang=ERRE>PROGRAM AMICABLE
 
CONST LIMIT=20000
Line 2,219:
IF (N=M2 AND N<M1) THEN PRINT(N,M1)
END FOR
END PROGRAM</langsyntaxhighlight>
{{out}}
<pre>Amicable pairs < 20000
Line 2,233:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang=fsharp>
[2..20000 - 1]
|> List.map (fun n-> n, ([1..n/2] |> List.filter (fun x->n % x = 0) |> List.sum))
Line 2,242:
|> List.map List.head
|> List.iter (printfn "%A")
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,258:
This solution focuses on the language's namesake: factoring code into small words which are subsequently composed to form more powerful — yet just as simple — words. Using this approach, the final word naturally arrives at the solution. This is often referred to as the bottom-up approach, which is a way in which Factor (and other concatenative languages) commonly differs from other languages.
 
<langsyntaxhighlight lang=Factor>
USING: grouping math.primes.factors math.ranges ;
 
Line 2,275:
 
print-am
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,295:
Calculate many times the divisors.
 
<langsyntaxhighlight lang=forth>: proper-divisors ( n -- 1..n )
dup 2 / 1+ 1 ?do
dup i mod 0= if i swap then
Line 2,318:
loop ;
 
20000 amicable-list</langsyntaxhighlight>
 
{{out}}
Line 2,333:
Use memory to store sum of divisors, a little quicker.
 
<langsyntaxhighlight lang=forth>variable amicable-table
 
: proper-divisors ( n -- 1..n )
Line 2,365:
build-amicable-table .amicables ;
 
20000 amicable-list</langsyntaxhighlight>
 
{{out}}
Line 2,394:
Amicable! 17296 18416
 
<langsyntaxhighlight lang=FORTRAN>
MODULE FACTORSTUFF !This protocol evades the need for multiple parameters, or COMMON, or one shapeless main line...
Concocted by R.N.McLean, MMXV.
Line 2,461:
END DO !On to the next.
END !Done.
</syntaxhighlight>
</lang>
 
=={{header|FreeBASIC}}==
===using Mod===
<langsyntaxhighlight lang=freebasic>
' FreeBASIC v1.05.0 win64
 
Line 2,501:
Sleep
End
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,517:
</pre>
===using "Sieve of Erathosthenes" style===
<langsyntaxhighlight lang=freebasic>' version 04-10-2016
' compile with: fbc -s console
' replaced the function with 2 FOR NEXT loops
Line 2,554:
Print : Print : Print " Hit any key to end program"
Sleep
End</langsyntaxhighlight>
<pre>
The pairs of amicable numbers below 20,000 are :
Line 2,569:
=={{header|Frink}}==
This example uses Frink's built-in efficient factorization algorithms. It can work for arbitrarily large numbers.
<langsyntaxhighlight lang=frink>
n = 1
seen = new set
Line 2,586:
}
} while n <= 20000
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,622:
let amicable = filter amicable (map (getPair divs) (iota (upper*upper)))
in map (fn (np,mp) => [#1 np, #1 mp]) amicable
</syntaxhighlight>
</lang>
 
=={{header|GFA Basic}}==
Line 2,668:
RETURN sum%
ENDFUNC
</syntaxhighlight>
</lang>
 
Output is:
Line 2,685:
 
=={{header|Go}}==
<langsyntaxhighlight lang=Go>package main
 
import "fmt"
Line 2,711:
}
}
}</langsyntaxhighlight>
 
{{output}}
Line 2,727:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang=Haskell>divisors :: (Integral a) => a -> [a]
divisors n = filter ((0 ==) . (n `mod`)) [1 .. (n `div` 2)]
 
Line 2,736:
pairs = [(n, m) | (n, nd) <- divs, (m, md) <- divs,
n < m, nd == m, md == n]
print pairs</langsyntaxhighlight>
{{out}}
<pre>[(220,284),(1184,1210),(2620,2924),(5020,5564),(6232,6368),(10744,10856),(12285,14595),(17296,18416)]</pre>
Line 2,743:
Or, deriving proper divisors above the square root as cofactors (for better performance)
 
<langsyntaxhighlight lang=Haskell>import Data.Bool (bool)
 
amicablePairsUpTo :: Int -> [(Int, Int)]
Line 2,763:
 
main :: IO ()
main = mapM_ print $ amicablePairsUpTo 20000</langsyntaxhighlight>
{{Out}}
<pre>(220,284)
Line 2,778:
[[Proper divisors#J|Proper Divisor implementation]]:
 
<langsyntaxhighlight lang=J>factors=: [: /:~@, */&>@{@((^ i.@>:)&.>/)@q:~&__
properDivisors=: factors -. -.&1</langsyntaxhighlight>
 
Amicable pairs:
 
<langsyntaxhighlight lang=J> 1 + 0 20000 #: I. ,(</~@i.@# * (* |:))(=/ +/@properDivisors@>) 1 + i.20000
220 284
1184 1210
Line 2,791:
10744 10856
12285 14595
17296 18416</langsyntaxhighlight>
 
=={{header|Java}}==
{{works with|Java|8}}
<langsyntaxhighlight lang=java>import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
Line 2,821:
return LongStream.rangeClosed(1, (n + 1) / 2).filter(i -> n % i == 0).sum();
}
}</langsyntaxhighlight>
 
<pre>220 284
Line 2,836:
===ES5===
 
<langsyntaxhighlight lang=JavaScript>(function (max) {
// Proper divisors
Line 2,896:
) + '\n\n' + JSON.stringify(pairs);
})(20000);</langsyntaxhighlight>
 
{{out}}
Line 2,921:
|}
 
<langsyntaxhighlight lang=JavaScript>[[220,284],[1184,1210],[2620,2924],[5020,5564],
[6232,6368],[10744,10856],[12285,14595],[17296,18416]]</langsyntaxhighlight>
 
===ES6===
 
<langsyntaxhighlight lang=JavaScript>(() => {
'use strict';
 
Line 2,986:
// MAIN ---
return main();
})();</langsyntaxhighlight>
{{Out}}
<pre>[220,284]
Line 2,998:
 
=={{header|jq}}==
<langsyntaxhighlight lang=jq># unordered
def proper_divisors:
. as $n
Line 3,023:
end ;
 
task(20000)</langsyntaxhighlight>
{{out}}
<langsyntaxhighlight lang=sh>$ jq -c -n -f amicable_pairs.jq
220 and 284 are amicable
1184 and 1210 are amicable
Line 3,033:
10744 and 10856 are amicable
12285 and 14595 are amicable
17296 and 18416 are amicable</langsyntaxhighlight>
 
=={{header|Julia}}==
Given <code>factor</code>, it is not necessary to calculate the individual divisors to compute their sum. See [[Abundant,_deficient_and_perfect_number_classifications#Julia|Abundant, deficient and perfect number classifications]] for the details.
It is safe to exclude primes from consideration; their proper divisor sum is always 1. This code also uses a minor trick to ensure that none of the numbers identified are above the limit. All numbers in the range are checked for an amicable partner, but the pair is cataloged only when the greater member is reached.
<langsyntaxhighlight lang=Julia>using Primes, Printf
 
function pcontrib(p::Int64, a::Int64)
Line 3,071:
 
amicables()
</langsyntaxhighlight>{{out}}
<pre>
Amicable pairs not greater than 20000000
Line 3,218:
 
=={{header|K}}==
<syntaxhighlight lang=k>
<lang k>
propdivs:{1+&0=x!'1+!x%2}
(8,2)#v@&{(x=+/propdivs[a])&~x=a:+/propdivs[x]}' v:1+!20000
Line 3,229:
12285 14595
17296 18416)
</syntaxhighlight>
</lang>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang=scala>// version 1.1
 
fun sumProperDivisors(n: Int): Int {
Line 3,248:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,267:
0.02 of a second in 16 lines of code.
The vital trick is to just set m to the sum of n's proper divisors each time. That way you only have to test the reverse, dividing your run time by half the loop limit (ie. 10,000)!
<langsyntaxhighlight lang=lua>function sumDivs (n)
local sum = 1
for d = 2, math.sqrt(n) do
Line 3,283:
if sumDivs(m) == n then print(n, m) end
end
end</langsyntaxhighlight>
 
{{out}}<pre>
Line 3,298:
=={{header|MAD}}==
 
<langsyntaxhighlight lang=MAD> NORMAL MODE IS INTEGER
DIMENSION DIVS(20000)
PRINT COMMENT $ AMICABLE PAIRS$
Line 3,322:
VECTOR VALUES AMI = $I6,I6*$
END OF PROGRAM</langsyntaxhighlight>
 
{{out}}
Line 3,342:
{{output?}}
 
<langsyntaxhighlight lang=Maple>
with(NumberTheory):
pairs:=[];
Line 3,356:
end do;
pairs;
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight lang=Mathematica>amicableQ[n_] :=
Module[{sum = Total[Most@Divisors@n]},
sum != n && n == Total[Most@Divisors@sum]]
 
Grid@Partition[Cases[Range[4, 20000], _?(amicableQ@# &)], 2]</langsyntaxhighlight>
 
{{out}}<pre>
Line 3,377:
 
=={{header|MATLAB}}==
<langsyntaxhighlight lang=Matlab>function amicable
tic
N=2:1:20000; aN=[];
Line 3,411:
K=1:ceil(x/2);
D=K(~(rem(x, K)));
end</langsyntaxhighlight>
 
{{out}}
Line 3,433:
Being a novice, I submitted my code to the Nim community for review and received much feedback and advice.
They were instrumental in fine-tuning this code for style and readability, I can't thank them enough.
<langsyntaxhighlight lang=Nim>
from math import sqrt
 
Line 3,452:
if m != 0 and n == sumProperDivisors(m, false):
echo $n, " ", $m
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,472:
Here's a second version that uses a large amount of memory but runs in 2m32seconds.
Again, thanks to the Nim community
<langsyntaxhighlight lang=Nim>
from math import sqrt
 
Line 3,490:
if n < m and n != 0 and m == x[n] + 1:
echo n, " ", m
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,509:
 
=={{header|Oberon-2}}==
<langsyntaxhighlight lang=Oberon2>
MODULE AmicablePairs;
IMPORT
Line 3,548:
END
END AmicablePairs.
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 3,565:
Using properDivs implementation tasks without optimization (calculating proper divisors sum without returning a list for instance) :
 
<langsyntaxhighlight lang=Oforth>import: mapping
 
Integer method: properDivs -- []
Line 3,578:
[ i, j ] over add
]
;</langsyntaxhighlight>
 
{{out}}
Line 3,587:
 
=={{header|OCaml}}==
<langsyntaxhighlight lang=ocaml>let rec isqrt n =
if n = 1 then 1
else let _n = isqrt (n - 1) in
Line 3,605:
if (sum_divs m) = n then Printf.printf "%d %d\n" n m;
done
</syntaxhighlight>
</lang>
{{out}}
<pre>220 284
Line 3,617:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang=parigp>for(x=1,20000,my(y=sigma(x)-x); if(y>x && x == sigma(y)-y,print(x" "y)))</langsyntaxhighlight>
{{out}}
<pre>220 284
Line 3,650:
Amicable! 17296,18416,
 
Source file:<langsyntaxhighlight lang=pascal>
Program SumOfFactors; uses crt; {Perpetrated by R.N.McLean, December MCMXCV}
//{$DEFINE ShowOverflow}
Line 3,739:
end;
Close (outf);
END.</langsyntaxhighlight>
 
===More expansive.===
a "normal" Version. Nearly fast as perl using nTheory.
<langsyntaxhighlight lang=pascal>program AmicablePairs;
{$IFDEF FPC}
{$MODE DELPHI}
Line 3,974:
writeln('Time to find amicable pairs ',FormatDateTime('HH:NN:SS.ZZZ' ,T2-T1));
{$IFNDEF UNIX} readln;{$ENDIF}
end.</langsyntaxhighlight>
Output
<pre> 1 220 284 ratio 1.2909091
Line 4,031:
Using "Sieve of Erathosthenes"-style
 
<langsyntaxhighlight lang=pascal>program AmicPair;
{find amicable pairs in a limited region 2..MAX
beware that >both< numbers must be smaller than MAX
Line 4,271:
readln;
{$ENDIF}
end.</langsyntaxhighlight>
output
<pre>
Line 4,322:
Not particularly clever, but instant for this example, and does up to 20 million in 11 seconds.
{{libheader|ntheory}}
<langsyntaxhighlight lang=perl>use ntheory qw/divisor_sum/;
for my $x (1..20000) {
my $y = divisor_sum($x)-$x;
say "$x $y" if $y > $x && $x == divisor_sum($y)-$y;
}</langsyntaxhighlight>
{{out}}
<pre>220 284
Line 4,338:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight lang=Phix>-->
<span style="color: #004080;">integer</span> <span style="color: #000000;">n</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">20000</span> <span style="color: #008080;">do</span>
Line 4,344:
<span style="color: #008080;">if</span> <span style="color: #000000;">m</span><span style="color: #0000FF;"><</span><span style="color: #000000;">n</span> <span style="color: #008080;">and</span> <span style="color: #000000;">m</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">sum</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">factors</span><span style="color: #0000FF;">(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">))</span> <span style="color: #008080;">then</span> <span style="color: #0000FF;">?{</span><span style="color: #000000;">m</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">}</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 4,358:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight lang=Phixmonti>def sumDivs
var n
1 var sum n sqrt
Line 4,379:
endfor
 
nl msec print " s" print</langsyntaxhighlight>
 
=={{header|PHP}}==
 
<langsyntaxhighlight lang=php><?php
 
function sumDivs ($n) {
Line 4,400:
}
 
?></langsyntaxhighlight>
{{out}}
<pre>220 284
Line 4,419:
 
Also, the calculation of the sum of divisors is tabled (the table is cleared between each run).
<langsyntaxhighlight lang=Picat>go =>
N = 20000,
 
Line 4,506:
sum_divisors(I,N,Sum0,Sum) =>
sum_divisors(I+1,N,Sum0,Sum).
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,529:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight lang=PicoLisp>(de accud (Var Key)
(if (assoc Key (val Var))
(con @ (inc (cdr @)))
Line 4,564:
(< I X)
(= I (factor-sum X))
(println I X) ) ) ) )</langsyntaxhighlight>
{{output}}
<pre>
Line 4,580:
=={{header|PL/I}}==
{{trans|REXX}}
<langsyntaxhighlight lang=pli>*process source xref;
ami: Proc Options(main);
p9a=time();
Line 4,639:
Return((p9c-p9b)/1000);
End;
End;</langsyntaxhighlight>
{{out}}
<pre> sum(pd) computed in 0.510 seconds elapsed
Line 4,654:
==={{header|PL/I-80}}===
Rather than populating an array with the sum of the proper divisors and then searching, the approach here performs an direct test, saving memory, and at a minimal penalty in execution speed, even though about 25% more calls are made to sumf() than would be required simply to initialize an array.
<langsyntaxhighlight lang=PL/I>
amicable: procedure options (main);
 
Line 4,702:
 
end amicable;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,718:
 
=={{header|PL/M}}==
<langsyntaxhighlight lang=plm>100H:
/* CP/M CALLS */
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
Line 4,761:
 
CALL EXIT;
EOF</langsyntaxhighlight>
{{out}}
<pre>220, 284
Line 4,774:
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
<langsyntaxhighlight lang=PowerShell>
function Get-ProperDivisorSum ( [int]$N )
{
Line 4,804:
 
Get-AmicablePairs 20000
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,823:
With some guidance from other solutions here:
 
<langsyntaxhighlight lang=prolog>divisor(N, Divisor) :-
UpperBound is round(sqrt(N)),
between(1, UpperBound, D),
Line 4,855:
amicable_pairs_under_20000(Pairs) :-
assoc_num_divsSum_in_range(1,20000, Assoc),
findall(P, get_amicable_pair(Assoc, P), Pairs).</langsyntaxhighlight>
 
Output:
 
<langsyntaxhighlight lang=prolog>?- amicable_pairs_under_20000(R).
R = [220-284, 1184-1210, 2620-2924, 5020-5564, 6232-6368, 10744-10856, 12285-14595, 17296-18416].</langsyntaxhighlight>
 
=={{header|PureBasic}}==
<langsyntaxhighlight lang=PureBasic>
EnableExplicit
 
Line 4,898:
CloseConsole()
EndIf
</syntaxhighlight>
</lang>
 
{{out}}
Line 4,916:
=={{header|Python}}==
Importing [[Proper_divisors#Python:_From_prime_factors|Proper divisors from prime factors]]:
<langsyntaxhighlight lang=python>from proper_divisors import proper_divs
 
def amicable(rangemax=20000):
Line 4,927:
for num, divsum in amicable():
print('Amicable pair: %i and %i With proper divisors:\n %r\n %r'
% (num, divsum, sorted(proper_divs(num)), sorted(proper_divs(divsum))))</langsyntaxhighlight>
 
{{out}}
Line 4,958:
Or, supplying our own '''properDivisors''' function, and defining the harvest in terms of a generic '''concatMap''':
 
<langsyntaxhighlight lang=python>'''Amicable pairs'''
 
from itertools import chain
Line 5,034:
# MAIN ---
if __name__ == '__main__':
main()</langsyntaxhighlight>
{{Out}}
<pre>(220, 284)
Line 5,049:
<code>properdivisors</code> is defined at [[Proper divisors#Quackery]].
 
<langsyntaxhighlight lang=Quackery> [ properdivisors
dup size 0 = iff
[ drop 0 ] done
Line 5,063:
nested join ] ] ] is amicables ( n --> [ )
20000 amicables witheach [ witheach [ echo sp ] cr ]</langsyntaxhighlight>
 
{{out}}
Line 5,080:
=={{header|R}}==
 
<syntaxhighlight lang=R>
<lang R>
divisors <- function (n) {
Filter( function (m) 0 == n %% m, 1:(n/2) )
Line 5,092:
cat(n, " ", m, "\n")
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,108:
=={{header|Racket}}==
With [[Proper_divisors#Racket]] in place:
<langsyntaxhighlight lang=racket>#lang racket
(require "proper-divisors.rkt")
(define SCOPE 20000)
Line 5,139:
EOS
n m n (proper-divisors n) m (proper-divisors m)))
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,179:
(formerly Perl 6)
{{Works with|Rakudo|2019.03.1}}
<langsyntaxhighlight lang=perl6>sub propdivsum (\x) {
my @l = 1 if x > 1;
(2 .. x.sqrt.floor).map: -> \d {
Line 5,190:
my $j = propdivsum($i);
say "$i $j" if $j > $i and $i == propdivsum($j);
}</langsyntaxhighlight>
{{out}}
<pre>220 284
Line 5,202:
 
=={{header|REBOL}}==
<langsyntaxhighlight lang=REBOL>;- based on Lua code ;-)
 
sum-of-divisors: func[n /local sum][
Line 5,217:
if n = sum-of-divisors m [ print [n tab m] ]
]
]</langsyntaxhighlight>
 
{{out}}
Line 5,232:
 
=={{header|ReScript}}==
<langsyntaxhighlight lang=rescript>let isqrt = (v) => {
Belt.Float.toInt(
sqrt(Belt.Int.toFloat(v)))
Line 5,257:
}
}
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 5,274:
=={{header|REXX}}==
===version 1, with factoring===
<langsyntaxhighlight lang=rexx>
/*REXX*/
 
Line 5,315:
sum=sum+word(list,i)
End
Return sum</langsyntaxhighlight>
{{out}}
<pre>sum(pd) computed in 48.502000 seconds
Line 5,339:
 
CPU time consumption note: &nbsp; for every doubling of &nbsp; '''H''' &nbsp; (the upper limit for searches), &nbsp; the CPU time consumed triples.
<langsyntaxhighlight lang=rexx>/*REXX program calculates and displays all amicable pairs up to a given number. */
parse arg H .; if H=='' | H=="," then H= 20000 /*get optional arguments (high limit).*/
w= length(H) ; low= 220 /*W: used for columnar output alignment*/
Line 5,366:
/* ___ */
if j*j==x then return s + j /*Was X a square? If so, add √ X */
return s /*return (sigma) sum of the divisors. */</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 5,386:
 
The optimization makes it about <u>another</u> &nbsp; '''30%''' &nbsp; faster when searching for amicable numbers up to one million.
<langsyntaxhighlight lang=rexx>/*REXX program calculates and displays all amicable pairs up to a given number. */
parse arg H .; if H=='' | H=="," then H=20000 /*get optional arguments (high limit).*/
w=length(H) ; low=220 /*W: used for columnar output alignment*/
Line 5,415:
/* ___ */
if j*j==x then return s + j /*Was X a square? If so, add √ X */
return s /*return (sigma) sum of the divisors. */</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 2<sup>nd</sup> REXX version.}} <br><br>
 
Line 5,423:
 
The optimization makes it about <u>another</u> &nbsp; '''20%''' &nbsp; faster when searching for amicable numbers up to one million.
<langsyntaxhighlight lang=rexx>/*REXX program calculates and displays all amicable pairs up to a given number. */
parse arg H .; if H=='' | H=="," then H=20000 /*get optional arguments (high limit).*/
w= length(H) ; low= 220 /*W: used for columnar output alignment*/
Line 5,456:
/* ___ */
if j*j==x then return s + j /*Was X a square? If so, add √ X */
return s /*return (sigma) sum of the divisors. */</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 2<sup>nd</sup> REXX version.}} <br><br>
 
Line 5,466:
 
The optimization makes it about <u>another</u> &nbsp; '''15%''' &nbsp; faster when searching for amicable numbers up to one million.
<langsyntaxhighlight lang=rexx>/*REXX program calculates and displays all amicable pairs up to a given number. */
parse arg H .; if H=='' | H=="," then H=20000 /*get optional arguments (high limit).*/
w= length(H) ; low= 220 /*W: used for columnar output alignment*/
Line 5,499:
/* ___ */
if j*j==x then return s + j /*Was X a square? If so, add √ X */
return s /*return (sigma) sum of the divisors. */</langsyntaxhighlight>
{{out|output|text=&nbsp; is identical to the 2<sup>nd</sup> REXX version.}} <br><br>
 
=={{header|Ring}}==
<langsyntaxhighlight lang=ring>
size = 18500
for n = 1 to size
Line 5,520:
next
return sum
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
With [[proper_divisors#Ruby]] in place:
<langsyntaxhighlight lang=ruby>h = {}
(1..20_000).each{|n| h[n] = n.proper_divisors.sum }
h.select{|k,v| h[v] == k && k < v}.each do |key,val| # k<v filters out doubles and perfects
puts "#{key} and #{val}"
end
</syntaxhighlight>
</lang>
{{out}}<pre>
220 and 284
Line 5,542:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang=Runbasic>size = 18500
for n = 1 to size
m = amicable(n)
Line 5,553:
if nr mod d = 0 then amicable = amicable + d + nr / d
next
end function</langsyntaxhighlight>
<pre>
220 and 284
Line 5,567:
=={{header|Rust}}==
 
<langsyntaxhighlight lang=rust>fn sum_of_divisors(val: u32) -> u32 {
(1..val/2+1).filter(|n| val % n == 0)
.fold(0, |sum, n| sum + n)
Line 5,581:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,595:
 
=={{header|Scala}}==
<langsyntaxhighlight lang=Scala>def properDivisors(n: Int) = (1 to n/2).filter(i => n % i == 0)
val divisorsSum = (1 to 20000).map(i => i -> properDivisors(i).sum).toMap
val result = divisorsSum.filter(v => v._1 < v._2 && divisorsSum.get(v._2) == Some(v._1))
 
println( result mkString ", " )</langsyntaxhighlight>
{{out}}
<pre>5020 -> 5564, 220 -> 284, 6232 -> 6368, 17296 -> 18416, 2620 -> 2924, 10744 -> 10856, 12285 -> 14595, 1184 -> 1210</pre>
Line 5,605:
=={{header|Scheme}}==
 
<langsyntaxhighlight lang=scheme>
(import (scheme base)
(scheme inexact)
Line 5,655:
(loop-j (+ 1 j))))
(loop-i (+ 1 i))))
</syntaxhighlight>
</lang>
 
{{out}}
Line 5,670:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang=ruby>func propdivsum(n) {
n.sigma - n
}
Line 5,677:
var j = propdivsum(i)
say "#{i} #{j}" if (j>i && i==propdivsum(j))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,691:
 
=={{header|Swift}}==
<langsyntaxhighlight lang=Swift>import func Darwin.sqrt
 
func sqrt(x:Int) -> Int { return Int(sqrt(Double(x))) }
Line 5,744:
}
}
}</langsyntaxhighlight>
===Alternative===
about 800 times faster.<langsyntaxhighlight lang=Swift>import func Darwin.sqrt
 
func sqrt(x:Int) -> Int { return Int(sqrt(Double(x))) }
Line 5,789:
}
 
amicables(20_000)</langsyntaxhighlight>
{{out}}
<pre>(220, 284)
Line 5,802:
 
=={{header|tbas}}==
<syntaxhighlight lang=vb>
<lang vb>
dim sums(20000)
 
Line 5,828:
next
next
</syntaxhighlight>
</lang>
<pre>
>tbas amicable_pairs.bas
Line 5,842:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang=tcl>proc properDivisors {n} {
if {$n == 1} return
set divs 1
Line 5,882:
puts "\t$m : $md"
puts "\t$n : $nd"
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,912:
 
=={{header|Transd}}==
<langsyntaxhighlight lang=scheme>
#lang transd
 
Line 5,931:
(textout (+ @idx 1) ", " i "\n")
)))))
}</langsyntaxhighlight>{{out}}
<pre>
284, 220
Line 5,992:
 
If (b@ > 1) c@ = c@ * (b@+1)
Return (c@)</langsyntaxhighlight>
{{Out}}
<pre>Limit: 20000
Line 6,008:
 
=={{header|UTFool}}==
<langsyntaxhighlight lang=UTFool>
···
http://rosettacode.org/wiki/Amicable_pairs
Line 6,027:
m +: n \ i = 0 ? i + (i = n / i ? 0 ! n / i) ! 0
⏎ m
</syntaxhighlight>
</lang>
 
=={{header|VBA}}==
<langsyntaxhighlight lang=vb>Option Explicit
Public Sub AmicablePairs()
Line 6,067:
If n Mod j = 0 Then S = j + S
Next
End Function</langsyntaxhighlight>
{{out}}
<pre>Execution Time : 7,95703125 seconds.
Line 6,082:
=={{header|VBScript}}==
Not at all optimal. :-(
<langsyntaxhighlight lang=VBScript>start = Now
Set nlookup = CreateObject("Scripting.Dictionary")
Set uniquepair = CreateObject("Scripting.Dictionary")
Line 6,117:
Next
 
WScript.Echo "Execution Time: " & DateDiff("s",Start,Now) & " seconds"</langsyntaxhighlight>
{{out}}
<pre>220:284
Line 6,131:
=={{header|Vlang}}==
{{trans|Go}}
<langsyntaxhighlight lang=Go>fn pfac_sum(i int) int {
mut sum := 0
for p := 1;p <= i/2;p++{
Line 6,150:
}
}
}</langsyntaxhighlight>
 
{{output}}
Line 6,170:
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<langsyntaxhighlight lang=ecmascript>import "/fmt" for Fmt
import "/math" for Int, Nums
 
Line 6,181:
System.print(" %(Fmt.d(5, n)) and %(Fmt.d(5, m))")
}
}</langsyntaxhighlight>
 
{{out}}
Line 6,197:
 
=={{header|XPL0}}==
<langsyntaxhighlight lang=XPL0>func SumDiv(Num); \Return sum of proper divisors of Num
int Num, Div, Sum, Quot;
[Div:= 2;
Line 6,223:
];
];
]</langsyntaxhighlight>
 
{{out}}
Line 6,239:
=={{header|Yabasic}}==
{{trans|Lua}}
<langsyntaxhighlight lang=Yabasic>sub sumDivs(n)
local sum, d
Line 6,260:
next
 
print : print peek("millisrunning"), " ms"</langsyntaxhighlight>
 
=={{header|zkl}}==
Slooooow
<langsyntaxhighlight lang=zkl>fcn properDivs(n){ [1.. (n + 1)/2 + 1].filter('wrap(x){ n%x==0 and n!=x }) }
const N=20000;
sums:=[1..N].pump(T(-1),fcn(n){ properDivs(n).sum(0) });
[0..].zip(sums).filter('wrap([(n,s)]){ (n<s<=N) and sums[s]==n }).println();</langsyntaxhighlight>
{{out}}
<pre>
Line 6,274:
 
=={{header|Zig}}==
<langsyntaxhighlight lang=zig>const MAXIMUM: u32 = 20_000;
 
// Fill up a given array with arr[n] = sum(propDivs(n))
Line 6,306:
}
}
}</langsyntaxhighlight>
{{out}}
<pre>220, 284
Line 6,319:
=={{header|ZX Spectrum Basic}}==
{{trans|AWK}}
<langsyntaxhighlight lang=zxbasic>10 LET limit=20000
20 PRINT "Amicable pairs < ";limit
30 FOR n=1 TO limit
Line 6,337:
1070 IF num/root=INT (num/root) THEN LET sum=sum+root
1080 LET num=sum
1090 RETURN</langsyntaxhighlight>
{{out}}
<pre>Amicable pairs < 20000
10,327

edits