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+ private static int sumOfDivisors (final int number ) {
20+ int sum = 0 ;
21+ final int root = (int ) Math .sqrt (number );
22+ for (int i = 1 ; i <= root ; i ++) {
23+ if (number % i == 0 ) {
24+ sum += i ;
25+ final int other = number / i ;
26+ if (other != i ) {
27+ sum += other ;
28+ }
29+ }
30+ }
31+ return sum ;
32+ }
33+
34+ /**
35+ * Checks whether two numbers are Friendly Numbers.
36+ *
37+ * @param a First number (must be positive)
38+ * @param b Second number (must be positive)
39+ * @return true if a and b are friendly numbers, false otherwise
40+ */
41+ public static boolean areFriendly (final int a , final int b ) {
42+ if (a <= 0 || b <= 0 ) {
43+ return false ;
44+ }
45+ final long sigmaA = sumOfDivisors (a );
46+ final long sigmaB = sumOfDivisors (b );
47+ return sigmaA * b == sigmaB * a ;
48+ }
49+ }
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