Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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
raklaptudirm merged 3 commits into TheAlgorithms:master from fun-guava:friendly_numbers
Nov 30, 2022
Merged
Changes from 2 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
41 changes: 41 additions & 0 deletions Maths/FriendlyNumbers.js
View file Open in desktop
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
/*
'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')
}

// Calculate the abundancy index of the two number.
// ... first get the sum of their divisors
let sumDivisorsFirstNumber = firstNumber
let sumDivisorsSecondNumber = secondNumber

for (let i = 0; i < firstNumber / 2; i++) {
if (Number.isInteger(firstNumber / i)) {
sumDivisorsFirstNumber += i
}
}
for (let i = 0; i < secondNumber / 2; i++) {
if (Number.isInteger(secondNumber / i)) {
sumDivisorsSecondNumber += i
}
}
// ... and divide that sum by the number itself
const abundancyIndexFirstNumber = sumDivisorsFirstNumber / firstNumber
const abundancyIndexSecondNumber = sumDivisorsSecondNumber / secondNumber

if (abundancyIndexFirstNumber === abundancyIndexSecondNumber) {
return true
} else {
return false
}
}

AltStyle によって変換されたページ (->オリジナル) /