forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
AmicableNumbersChecker.cs
34 lines (31 loc) · 1.14 KB
/
AmicableNumbersChecker.cs
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
namespace Algorithms.Numeric;
/// <summary>
/// Amicable numbers are two different natural numbers related in such a way that the sum of the proper divisors of
/// each is equal to the other number. That is, σ(a)=b+a and σ(b)=a+b, where σ(n) is equal to the sum of positive divisors of n (see also divisor function).
/// See <a href="https://en.wikipedia.org/wiki/Amicable_numbers">here</a> for more info.
/// </summary>
public static class AmicableNumbersChecker
{
/// <summary>
/// Checks if two numbers are amicable or not.
/// </summary>
/// <param name="x">First number to check.</param>
/// <param name="y">Second number to check.</param>
/// <returns>True if they are amicable numbers. False if not.</returns>
public static bool AreAmicableNumbers(int x, int y)
{
return SumOfDivisors(x) == y && SumOfDivisors(y) == x;
}
private static int SumOfDivisors(int number)
{
var sum = 0; /* sum of its positive divisors */
for (var i = 1; i < number; ++i)
{
if (number % i == 0)
{
sum += i;
}
}
return sum;
}
}