File tree Expand file tree Collapse file tree
main/java/com/thealgorithms/maths
test/java/com/thealgorithms/maths Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .thealgorithms .maths ;
2+
3+ /**
4+ * Two numbers are Friendly if they share the same abundancy index,
5+ * which is the ratio of the sum of divisors to the number itself.
6+ * Example: 6 and 28 are friendly because sigma(6)/6 = 2 and sigma(28)/28 = 2
7+ *
8+ * @see <a href="https://en.wikipedia.org/wiki/Friendly_number">
9+ * Wikipedia: Friendly Number</a>
10+ *
11+ * author: Vraj Prajapati @Rosander0
12+ */
13+ public final class FriendlyNumber {
14+
15+ private FriendlyNumber () {
16+ // Utility class
17+ }
18+
19+ static int sumOfDivisors (final int number ) {
20+ int sum = 0 ;
21+ for (int i = 1 ; i <= number ; i ++) {
22+ if (number % i == 0 ) {
23+ sum += i ;
24+ }
25+ }
26+ return sum ;
27+ }
28+
29+ /**
30+ * Checks whether two numbers are Friendly Numbers.
31+ * Two numbers are friendly if they share the same abundancy index
32+ * (sumOfDivisors / number), compared via cross multiplication to avoid
33+ * floating point errors.
34+ *
35+ * @param a First number (must be positive)
36+ * @param b Second number (must be positive)
37+ * @return true if a and b are friendly numbers, false otherwise
38+ */
39+ public static boolean areFriendly (final int a , final int b ) {
40+ if (a <= 0 || b <= 0 ) {
41+ return false ;
42+ }
43+ int sigmaA = sumOfDivisors (a );
44+ int sigmaB = sumOfDivisors (b );
45+ return sigmaA * b == sigmaB * a ;
46+ }
47+ }
Original file line number Diff line number Diff line change 1+ package com .thealgorithms .maths ;
2+ // author: Vraj Prajapati @Rosander0
3+
4+ import static org .junit .jupiter .api .Assertions .assertFalse ;
5+ import static org .junit .jupiter .api .Assertions .assertTrue ;
6+
7+ import org .junit .jupiter .api .Test ;
8+
9+ public class FriendlyNumberTest {
10+
11+ @ Test
12+ public void testFriendlyNumbers () {
13+ // 6 and 28 are friendly (abundancy index = 2)
14+ assertTrue (FriendlyNumber .areFriendly (6 , 28 ));
15+ // Every number is friendly with itself
16+ assertTrue (FriendlyNumber .areFriendly (6 , 6 ));
17+ assertTrue (FriendlyNumber .areFriendly (1 , 1 ));
18+ }
19+
20+ @ Test
21+ public void testNonFriendlyNumbers () {
22+ assertFalse (FriendlyNumber .areFriendly (6 , 10 ));
23+ assertFalse (FriendlyNumber .areFriendly (10 , 15 ));
24+ assertFalse (FriendlyNumber .areFriendly (4 , 9 ));
25+ }
26+
27+ @ Test
28+ public void testInvalidInputs () {
29+ assertFalse (FriendlyNumber .areFriendly (0 , 6 ));
30+ assertFalse (FriendlyNumber .areFriendly (-1 , 6 ));
31+ assertFalse (FriendlyNumber .areFriendly (6 , -1 ));
32+ }
33+ }
You can’t perform that action at this time.
0 commit comments