-
Notifications
You must be signed in to change notification settings - Fork 21.2k
Expand file tree
/
Copy pathFriendlyNumber.java
More file actions
47 lines (43 loc) · 1.38 KB
/
Copy pathFriendlyNumber.java
File metadata and controls
47 lines (43 loc) · 1.38 KB
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
package com.thealgorithms.maths;
/**
* Two numbers are Friendly if they share the same abundancy index,
* which is the ratio of the sum of divisors to the number itself.
* Example: 6 and 28 are friendly because sigma(6)/6 = 2 and sigma(28)/28 = 2
*
* @see <a href="https://en.wikipedia.org/wiki/Friendly_number">
* Wikipedia: Friendly Number</a>
*
* author: Vraj Prajapati @Rosander0
*/
public final class FriendlyNumber {
private FriendlyNumber() {
// Utility class
}
static int sumOfDivisors(final int number) {
int sum = 0;
for (int i = 1; i <= number; i++) {
if (number % i == 0) {
sum += i;
}
}
return sum;
}
/**
* Checks whether two numbers are Friendly Numbers.
* Two numbers are friendly if they share the same abundancy index
* (sumOfDivisors / number), compared via cross multiplication to avoid
* floating point errors.
*
* @param a First number (must be positive)
* @param b Second number (must be positive)
* @return true if a and b are friendly numbers, false otherwise
*/
public static boolean areFriendly(final int a, final int b) {
if (a <= 0 || b <= 0) {
return false;
}
int sigmaA = sumOfDivisors(a);
int sigmaB = sumOfDivisors(b);
return sigmaA * b == sigmaB * a;
}
}