Amicable pairs: Difference between revisions
Content deleted Content added
Thundergnat (talk | contribs) m syntax highlighting fixup automation |
|||
Line 21:
=={{header|11l}}==
<
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)</
=={{header|8080 Assembly}}==
<
;;; 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</
{{out}}
<pre>220 284
Line 163:
=={{header|8086 Assembly}}==
<
cpu 8086
org 100h
Line 252:
nbuf: db ' $'
nl: db 13,10,'$'
final: equ $</
{{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 }}
<
/* 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>
<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}}
<
CARD FUNC SumDivisors(CARD x)
Line 480:
FI
OD
RETURN</
{{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]].
<
procedure Amicable_Pairs is
Line 518:
end if;
end loop;
end Amicable_Pairs;</
{{Out}}
<pre>
Line 533:
=={{header|ALGOL 60}}==
{{works with|A60}}
<
begin
Line 585:
end
</syntaxhighlight>
{{out}}
<pre>
Line 601:
=={{header|ALGOL 68}}==
<
# if n = 1, 0 or -1, we return 0 #
PROC sum proper divisors = ( INT n )INT:
Line 643:
FI
OD
OD</
{{out}}
<pre>
Line 660:
{{Trans|GFA Basic}}
<
110 CLEAR
120 !
Line 698:
460 END IF
470 LET sum_proper_divisors = sum
480 END FUNCTION</
=={{header|AppleScript}}==
Line 704:
{{Trans|JavaScript}}
<
-- amicablePairsUpTo :: Int -> Int
Line 846:
end script
end if
end mReturn</
{{Out}}
<
{6232, 6368}, {10744, 10856}, {12285, 14595}, {17296, 18416}}</
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi <br> or android 32 bits with application Termux}}
<
/* ARM assembly Raspberry PI or android with termux */
/* program amicable.s */
Line 1,004:
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
<pre>
220 : 284
Line 1,016:
</pre>
=={{header|Arturo}}==
<
(factors x) -- x
Line 1,035:
]
print unique amicables</
{{out}}
Line 1,042:
=={{header|ATS}}==
<
(* ****** ****** *)
//
Line 1,147:
(* ****** ****** *)
</syntaxhighlight>
{{out}}
Line 1,162:
=={{header|AutoHotkey}}==
<
Loop, 20000
{
Line 1,214:
}
MsgBox % final
ExitApp</
{{out}}
<pre>
Line 1,228:
=={{header|AWK}}==
<
#!/bin/awk -f
function sumprop(num, i,sum,root) {
Line 1,256:
}
}
}</
{{out}}
<pre>
Line 1,274:
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<
if number < 2 then return 0
sum = 0
Line 1,298:
end if
next n
end</
{{out}}
<pre>The pairs of amicable numbers below 20,000 are :
Line 1,313:
=={{header|BCPL}}==
<
manifest $(
Line 1,342:
if amicable(pds, x, y) do
writef("%N, %N*N", x, y)
$)</
{{out}}
Line 1,356:
=={{header|Befunge}}==
<
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*:*:*%:*\`!^</
{{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)
<
#include <stdlib.h>
Line 1,433:
printf("\nTop %u count : %u\n",top,cnt);
return 0;
}</
{{out}}
<pre>
Line 1,462:
=={{header|C sharp|C#}}==
<
using System.Collections.Generic;
using System.Linq;
Line 1,498:
}
}
}</
{{out}}
<pre>
Line 1,512:
=={{header|C++}}==
<
#include <vector>
#include <unordered_map>
Line 1,561:
std::cout << count << " amicable pairs discovered" << std::endl;
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,576:
=={{header|Clojure}}==
<
(ns example
(:gen-class))
Line 1,600:
(doseq [q find-pairs]
(println q))
</syntaxhighlight>
{{Out}}
<pre>
Line 1,614:
=={{header|CLU}}==
<
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</
{{out}}
<pre>220, 284
Line 1,655:
=={{header|Common Lisp}}==
<
(defun sum-proper-divisors (n)
(or (gethash n cache)
Line 1,669:
collect (list x sum-divs)))
(amicable-pairs-up-to 20000)</
{{out}}
<pre>((220 284) (1184 1210) (2620 2924) (5020 5564) (6232 6368) (10744 10856)
Line 1,675:
=={{header|Cowgol}}==
<
const LIMIT := 20000;
Line 1,714:
end loop;
i := i + 1;
end loop;</
{{out}}
<pre>220, 284
Line 1,726:
=={{header|Crystal}}==
<
MX = 524_000_000
N = Math.sqrt(MX).to_u32
Line 1,747:
end
}
</syntaxhighlight>
{{out}}
<pre>
Line 1,767:
=={{header|D}}==
{{trans|Python}}
<
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));
}</
{{out}}
<pre>Amicable pair: 220 and 284 with proper divisors:
Line 1,811:
=={{header|Draco}}==
<
* P[n] is the sum of proper divisors of N */
proc nonrec propdivs([*] word p) void:
Line 1,838:
od
od
corp</
{{out}}
<pre> 220, 284
Line 1,850:
=={{header|EchoLisp}}==
<
;; using (sum-divisors) from math.lib
Line 1,869:
→ (... (802725 . 863835) (879712 . 901424) (898216 . 980984) (947835 . 1125765) (998104 . 1043096))
</syntaxhighlight>
=={{header|Ela}}==
{{trans|Haskell}}
<
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</
{{out}}
Line 1,889:
{{trans|C#}}
ELENA 5.0 :
<
import system'routines;
Line 1,924:
console.printLine(pair.Item1, " ", pair.Item2)
}
}</
{{out}}
<pre>
Line 1,937:
</pre>
=== Alternative variant using strong-typed closures ===
<
import system'routines'stex;
import system'collections;
Line 1,970:
console.printLine(pair.Item1, " ", pair.Item2)
}
}</
=== Alternative variant using yield enumerator ===
<
import system'routines'stex;
import system'collections;
Line 2,016:
console.printLine(pair.Item1, " ", pair.Item2)
}
}</
{{out}}
<pre>
Line 2,032:
{{works with|Elixir|1.2}}
With [[proper_divisors#Elixir]] in place:
<
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)</
{{out}}
Line 2,063:
Very slow solution. Same functions by and large as in proper divisors and co.
<
-module(properdivs).
-export([amicable/1,divs/1,sumdivs/1]).
Line 2,099:
sumdivs(N) -> lists:sum(divs(N)).
</
{{out}}
<pre>
Line 2,135:
[See the talk section '''amicable pairs, out of order''' for this Rosetta Code task.]
<
friendly(Limit) ->
List = [{X,properdivs:sumdivs(X)} || X <- lists:seq(3,Limit)],
Line 2,144:
io:format("L: ~w~n", [Final]).
</syntaxhighlight>
{{output}}
Line 2,154:
We might answer a challenge by saying:
<
friendly(Limit) ->
List = [{X,properdivs:sumdivs(X)} || X <- lists:seq(3,Limit)],
Line 2,175:
end.
</syntaxhighlight>
{{out}}
<pre>
Line 2,192:
=={{header|ERRE}}==
<
CONST LIMIT=20000
Line 2,219:
IF (N=M2 AND N<M1) THEN PRINT(N,M1)
END FOR
END PROGRAM</
{{out}}
<pre>Amicable pairs < 20000
Line 2,233:
=={{header|F_Sharp|F#}}==
<
[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>
{{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.
<
USING: grouping math.primes.factors math.ranges ;
Line 2,275:
print-am
</syntaxhighlight>
{{out}}
<pre>
Line 2,295:
Calculate many times the divisors.
<
dup 2 / 1+ 1 ?do
dup i mod 0= if i swap then
Line 2,318:
loop ;
20000 amicable-list</
{{out}}
Line 2,333:
Use memory to store sum of divisors, a little quicker.
<
: proper-divisors ( n -- 1..n )
Line 2,365:
build-amicable-table .amicables ;
20000 amicable-list</
{{out}}
Line 2,394:
Amicable! 17296 18416
<
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>
=={{header|FreeBASIC}}==
===using Mod===
<
' FreeBASIC v1.05.0 win64
Line 2,501:
Sleep
End
</syntaxhighlight>
{{out}}
Line 2,517:
</pre>
===using "Sieve of Erathosthenes" style===
<
' 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</
<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.
<
n = 1
seen = new set
Line 2,586:
}
} while n <= 20000
</syntaxhighlight>
{{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>
=={{header|GFA Basic}}==
Line 2,668:
RETURN sum%
ENDFUNC
</syntaxhighlight>
Output is:
Line 2,685:
=={{header|Go}}==
<
import "fmt"
Line 2,711:
}
}
}</
{{output}}
Line 2,727:
=={{header|Haskell}}==
<
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</
{{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)
<
amicablePairsUpTo :: Int -> [(Int, Int)]
Line 2,763:
main :: IO ()
main = mapM_ print $ amicablePairsUpTo 20000</
{{Out}}
<pre>(220,284)
Line 2,778:
[[Proper divisors#J|Proper Divisor implementation]]:
<
properDivisors=: factors -. -.&1</
Amicable pairs:
<
220 284
1184 1210
Line 2,791:
10744 10856
12285 14595
17296 18416</
=={{header|Java}}==
{{works with|Java|8}}
<
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();
}
}</
<pre>220 284
Line 2,836:
===ES5===
<
// Proper divisors
Line 2,896:
) + '\n\n' + JSON.stringify(pairs);
})(20000);</
{{out}}
Line 2,921:
|}
<
[6232,6368],[10744,10856],[12285,14595],[17296,18416]]</
===ES6===
<
'use strict';
Line 2,986:
// MAIN ---
return main();
})();</
{{Out}}
<pre>[220,284]
Line 2,998:
=={{header|jq}}==
<
def proper_divisors:
. as $n
Line 3,023:
end ;
task(20000)</
{{out}}
<
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</
=={{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.
<
function pcontrib(p::Int64, a::Int64)
Line 3,071:
amicables()
</
<pre>
Amicable pairs not greater than 20000000
Line 3,218:
=={{header|K}}==
<syntaxhighlight 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>
=={{header|Kotlin}}==
<
fun sumProperDivisors(n: Int): Int {
Line 3,248:
}
}
}</
{{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)!
<
local sum = 1
for d = 2, math.sqrt(n) do
Line 3,283:
if sumDivs(m) == n then print(n, m) end
end
end</
{{out}}<pre>
Line 3,298:
=={{header|MAD}}==
<
DIMENSION DIVS(20000)
PRINT COMMENT $ AMICABLE PAIRS$
Line 3,322:
VECTOR VALUES AMI = $I6,I6*$
END OF PROGRAM</
{{out}}
Line 3,342:
{{output?}}
<
with(NumberTheory):
pairs:=[];
Line 3,356:
end do;
pairs;
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
Module[{sum = Total[Most@Divisors@n]},
sum != n && n == Total[Most@Divisors@sum]]
Grid@Partition[Cases[Range[4, 20000], _?(amicableQ@# &)], 2]</
{{out}}<pre>
Line 3,377:
=={{header|MATLAB}}==
<
tic
N=2:1:20000; aN=[];
Line 3,411:
K=1:ceil(x/2);
D=K(~(rem(x, K)));
end</
{{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.
<
from math import sqrt
Line 3,452:
if m != 0 and n == sumProperDivisors(m, false):
echo $n, " ", $m
</syntaxhighlight>
{{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
<
from math import sqrt
Line 3,490:
if n < m and n != 0 and m == x[n] + 1:
echo n, " ", m
</syntaxhighlight>
{{out}}
<pre>
Line 3,509:
=={{header|Oberon-2}}==
<
MODULE AmicablePairs;
IMPORT
Line 3,548:
END
END AmicablePairs.
</syntaxhighlight>
{{Out}}
<pre>
Line 3,565:
Using properDivs implementation tasks without optimization (calculating proper divisors sum without returning a list for instance) :
<
Integer method: properDivs -- []
Line 3,578:
[ i, j ] over add
]
;</
{{out}}
Line 3,587:
=={{header|OCaml}}==
<
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>
{{out}}
<pre>220 284
Line 3,617:
=={{header|PARI/GP}}==
<
{{out}}
<pre>220 284
Line 3,650:
Amicable! 17296,18416,
Source file:<
Program SumOfFactors; uses crt; {Perpetrated by R.N.McLean, December MCMXCV}
//{$DEFINE ShowOverflow}
Line 3,739:
end;
Close (outf);
END.</
===More expansive.===
a "normal" Version. Nearly fast as perl using nTheory.
<
{$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.</
Output
<pre> 1 220 284 ratio 1.2909091
Line 4,031:
Using "Sieve of Erathosthenes"-style
<
{find amicable pairs in a limited region 2..MAX
beware that >both< numbers must be smaller than MAX
Line 4,271:
readln;
{$ENDIF}
end.</
output
<pre>
Line 4,322:
Not particularly clever, but instant for this example, and does up to 20 million in 11 seconds.
{{libheader|ntheory}}
<
for my $x (1..20000) {
my $y = divisor_sum($x)-$x;
say "$x $y" if $y > $x && $x == divisor_sum($y)-$y;
}</
{{out}}
<pre>220 284
Line 4,338:
=={{header|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>
<!--</
{{out}}
<pre>
Line 4,358:
=={{header|Phixmonti}}==
<
var n
1 var sum n sqrt
Line 4,379:
endfor
nl msec print " s" print</
=={{header|PHP}}==
<
function sumDivs ($n) {
Line 4,400:
}
?></
{{out}}
<pre>220 284
Line 4,419:
Also, the calculation of the sum of divisors is tabled (the table is cleared between each run).
<
N = 20000,
Line 4,506:
sum_divisors(I,N,Sum0,Sum) =>
sum_divisors(I+1,N,Sum0,Sum).
</syntaxhighlight>
{{out}}
Line 4,529:
=={{header|PicoLisp}}==
<
(if (assoc Key (val Var))
(con @ (inc (cdr @)))
Line 4,564:
(< I X)
(= I (factor-sum X))
(println I X) ) ) ) )</
{{output}}
<pre>
Line 4,580:
=={{header|PL/I}}==
{{trans|REXX}}
<
ami: Proc Options(main);
p9a=time();
Line 4,639:
Return((p9c-p9b)/1000);
End;
End;</
{{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.
<
amicable: procedure options (main);
Line 4,702:
end amicable;
</syntaxhighlight>
{{out}}
<pre>
Line 4,718:
=={{header|PL/M}}==
<
/* CP/M CALLS */
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
Line 4,761:
CALL EXIT;
EOF</
{{out}}
<pre>220, 284
Line 4,774:
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
<
function Get-ProperDivisorSum ( [int]$N )
{
Line 4,804:
Get-AmicablePairs 20000
</syntaxhighlight>
{{out}}
<pre>
Line 4,823:
With some guidance from other solutions here:
<
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).</
Output:
<
R = [220-284, 1184-1210, 2620-2924, 5020-5564, 6232-6368, 10744-10856, 12285-14595, 17296-18416].</
=={{header|PureBasic}}==
<
EnableExplicit
Line 4,898:
CloseConsole()
EndIf
</syntaxhighlight>
{{out}}
Line 4,916:
=={{header|Python}}==
Importing [[Proper_divisors#Python:_From_prime_factors|Proper divisors from prime factors]]:
<
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))))</
{{out}}
Line 4,958:
Or, supplying our own '''properDivisors''' function, and defining the harvest in terms of a generic '''concatMap''':
<
from itertools import chain
Line 5,034:
# MAIN ---
if __name__ == '__main__':
main()</
{{Out}}
<pre>(220, 284)
Line 5,049:
<code>properdivisors</code> is defined at [[Proper divisors#Quackery]].
<
dup size 0 = iff
[ drop 0 ] done
Line 5,063:
nested join ] ] ] is amicables ( n --> [ )
20000 amicables witheach [ witheach [ echo sp ] cr ]</
{{out}}
Line 5,080:
=={{header|R}}==
<syntaxhighlight lang=R>
divisors <- function (n) {
Filter( function (m) 0 == n %% m, 1:(n/2) )
Line 5,092:
cat(n, " ", m, "\n")
}
</syntaxhighlight>
{{out}}
Line 5,108:
=={{header|Racket}}==
With [[Proper_divisors#Racket]] in place:
<
(require "proper-divisors.rkt")
(define SCOPE 20000)
Line 5,139:
EOS
n m n (proper-divisors n) m (proper-divisors m)))
</syntaxhighlight>
{{out}}
Line 5,179:
(formerly Perl 6)
{{Works with|Rakudo|2019.03.1}}
<
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);
}</
{{out}}
<pre>220 284
Line 5,202:
=={{header|REBOL}}==
<
sum-of-divisors: func[n /local sum][
Line 5,217:
if n = sum-of-divisors m [ print [n tab m] ]
]
]</
{{out}}
Line 5,232:
=={{header|ReScript}}==
<
Belt.Float.toInt(
sqrt(Belt.Int.toFloat(v)))
Line 5,257:
}
}
</syntaxhighlight>
{{output}}
<pre>
Line 5,274:
=={{header|REXX}}==
===version 1, with factoring===
<
/*REXX*/
Line 5,315:
sum=sum+word(list,i)
End
Return sum</
{{out}}
<pre>sum(pd) computed in 48.502000 seconds
Line 5,339:
CPU time consumption note: for every doubling of '''H''' (the upper limit for searches), the CPU time consumed triples.
<
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. */</
{{out|output|text= when using the default input:}}
<pre>
Line 5,386:
The optimization makes it about <u>another</u> '''30%''' faster when searching for amicable numbers up to one million.
<
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. */</
{{out|output|text= is identical to the 2<sup>nd</sup> REXX version.}} <br><br>
Line 5,423:
The optimization makes it about <u>another</u> '''20%''' faster when searching for amicable numbers up to one million.
<
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. */</
{{out|output|text= is identical to the 2<sup>nd</sup> REXX version.}} <br><br>
Line 5,466:
The optimization makes it about <u>another</u> '''15%''' faster when searching for amicable numbers up to one million.
<
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. */</
{{out|output|text= is identical to the 2<sup>nd</sup> REXX version.}} <br><br>
=={{header|Ring}}==
<
size = 18500
for n = 1 to size
Line 5,520:
next
return sum
</syntaxhighlight>
=={{header|Ruby}}==
With [[proper_divisors#Ruby]] in place:
<
(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>
{{out}}<pre>
220 and 284
Line 5,542:
=={{header|Run BASIC}}==
<
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</
<pre>
220 and 284
Line 5,567:
=={{header|Rust}}==
<
(1..val/2+1).filter(|n| val % n == 0)
.fold(0, |sum, n| sum + n)
Line 5,581:
}
}
}</
{{out}}
<pre>
Line 5,595:
=={{header|Scala}}==
<
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 ", " )</
{{out}}
<pre>5020 -> 5564, 220 -> 284, 6232 -> 6368, 17296 -> 18416, 2620 -> 2924, 10744 -> 10856, 12285 -> 14595, 1184 -> 1210</pre>
Line 5,605:
=={{header|Scheme}}==
<
(import (scheme base)
(scheme inexact)
Line 5,655:
(loop-j (+ 1 j))))
(loop-i (+ 1 i))))
</syntaxhighlight>
{{out}}
Line 5,670:
=={{header|Sidef}}==
<
n.sigma - n
}
Line 5,677:
var j = propdivsum(i)
say "#{i} #{j}" if (j>i && i==propdivsum(j))
}</
{{out}}
<pre>
Line 5,691:
=={{header|Swift}}==
<
func sqrt(x:Int) -> Int { return Int(sqrt(Double(x))) }
Line 5,744:
}
}
}</
===Alternative===
about 800 times faster.<
func sqrt(x:Int) -> Int { return Int(sqrt(Double(x))) }
Line 5,789:
}
amicables(20_000)</
{{out}}
<pre>(220, 284)
Line 5,802:
=={{header|tbas}}==
<syntaxhighlight lang=vb>
dim sums(20000)
Line 5,828:
next
next
</syntaxhighlight>
<pre>
>tbas amicable_pairs.bas
Line 5,842:
=={{header|Tcl}}==
<
if {$n == 1} return
set divs 1
Line 5,882:
puts "\t$m : $md"
puts "\t$n : $nd"
}</
{{out}}
<pre>
Line 5,912:
=={{header|Transd}}==
<
#lang transd
Line 5,931:
(textout (+ @idx 1) ", " i "\n")
)))))
}</
<pre>
284, 220
Line 5,992:
If (b@ > 1) c@ = c@ * (b@+1)
Return (c@)</
{{Out}}
<pre>Limit: 20000
Line 6,008:
=={{header|UTFool}}==
<
···
http://rosettacode.org/wiki/Amicable_pairs
Line 6,027:
m +: n \ i = 0 ? i + (i = n / i ? 0 ! n / i) ! 0
⏎ m
</syntaxhighlight>
=={{header|VBA}}==
<
Public Sub AmicablePairs()
Line 6,067:
If n Mod j = 0 Then S = j + S
Next
End Function</
{{out}}
<pre>Execution Time : 7,95703125 seconds.
Line 6,082:
=={{header|VBScript}}==
Not at all optimal. :-(
<
Set nlookup = CreateObject("Scripting.Dictionary")
Set uniquepair = CreateObject("Scripting.Dictionary")
Line 6,117:
Next
WScript.Echo "Execution Time: " & DateDiff("s",Start,Now) & " seconds"</
{{out}}
<pre>220:284
Line 6,131:
=={{header|Vlang}}==
{{trans|Go}}
<
mut sum := 0
for p := 1;p <= i/2;p++{
Line 6,150:
}
}
}</
{{output}}
Line 6,170:
{{libheader|Wren-fmt}}
{{libheader|Wren-math}}
<
import "/math" for Int, Nums
Line 6,181:
System.print(" %(Fmt.d(5, n)) and %(Fmt.d(5, m))")
}
}</
{{out}}
Line 6,197:
=={{header|XPL0}}==
<
int Num, Div, Sum, Quot;
[Div:= 2;
Line 6,223:
];
];
]</
{{out}}
Line 6,239:
=={{header|Yabasic}}==
{{trans|Lua}}
<
local sum, d
Line 6,260:
next
print : print peek("millisrunning"), " ms"</
=={{header|zkl}}==
Slooooow
<
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();</
{{out}}
<pre>
Line 6,274:
=={{header|Zig}}==
<
// Fill up a given array with arr[n] = sum(propDivs(n))
Line 6,306:
}
}
}</
{{out}}
<pre>220, 284
Line 6,319:
=={{header|ZX Spectrum Basic}}==
{{trans|AWK}}
<
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</
{{out}}
<pre>Amicable pairs < 20000
|