forked from TheAlgorithms/JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FriendlyNumbers.js
38 lines (33 loc) · 1.21 KB
/
FriendlyNumbers.js
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
/*
'In number theory, friendly numbers are two or more natural numbers with a common abundancy index, the
ratio between the sum of divisors of a number and the number itself.'
Source: https://en.wikipedia.org/wiki/Friendly_number
See also: https://mathworld.wolfram.com/FriendlyNumber.html#:~:text=The%20numbers%20known%20to%20be,numbers%20have%20a%20positive%20density.
*/
export const FriendlyNumbers = (firstNumber, secondNumber) => {
// input: two integers
// output: true if the two integers are friendly numbers, false if they are not friendly numbers
// First, check that the parameters are valid
if (
!Number.isInteger(firstNumber) ||
!Number.isInteger(secondNumber) ||
firstNumber === 0 ||
secondNumber === 0 ||
firstNumber === secondNumber
) {
throw new Error('The two parameters must be distinct, non-null integers')
}
return abundancyIndex(firstNumber) === abundancyIndex(secondNumber)
}
function abundancyIndex(number) {
return sumDivisors(number) / number
}
function sumDivisors(number) {
let runningSumDivisors = number
for (let i = 0; i < number / 2; i++) {
if (Number.isInteger(number / i)) {
runningSumDivisors += i
}
}
return runningSumDivisors
}