Skip to content

Added a new Maths algorithm to determine if two non-null integers are "friendly numbers" #1267

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Nov 30, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions Maths/FriendlyNumbers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
'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
}