-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuddy_pairs_unit.pas
More file actions
64 lines (54 loc) · 929 Bytes
/
buddy_pairs_unit.pas
File metadata and controls
64 lines (54 loc) · 929 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
{
5 kyu
Buddy Pairs
https://www.codewars.com/kata/59ccf051dcc4050f7800008f
}
unit buddy_pairs_unit;
{$mode objfpc}{$H+}
interface
type
TBuddy = array [0..1] of int64;
const
noBuddy: TBuddy = (-1, -1);
function Buddy(start, limit: int64): TBuddy;
implementation
function SumDivisors(n: int64): int64;
var
i, sum: int64;
begin
if n <= 1 then
Exit(0);
sum := 1;
i := 2;
while i * i <= n do
begin
if n mod i = 0 then
begin
sum := sum + i;
if i <> n div i then
sum := sum + (n div i);
end;
Inc(i);
end;
Result := sum;
end;
function Buddy(start, limit: int64): TBuddy;
var
n, m: int64;
begin
for n := start to limit do
begin
m := SumDivisors(n) - 1;
if m > n then
begin
if SumDivisors(m) = n + 1 then
begin
Result[0] := n;
Result[1] := m;
Exit(Result);
end;
end;
end;
Result := noBuddy;
end;
end.