The Program in C++ Program to Check if two numbers are Amicable numbers or not is given below:
#include <iostream>
#include <cmath>
using namespace std;
int sumOfDivisors(int n) {
int sum = 0;
for (int i = 1; i <= sqrt(n); i++) {
if (n % i == 0) {
if (i == (n / i)) {
sum += i;
} else {
sum += i + n / i;
}
}
}
return sum - n;
}
bool areAmicableNumbers(int a, int b) {
return sumOfDivisors(a) == b && sumOfDivisors(b) == a;
}
int main() {
int a, b;
cout << "Hello Codeauri Family,Enter two numbers here if it is amicable number or not!:\n ";
cin >> a >> b;
if (areAmicableNumbers(a, b)) {
cout << a << " and " << b << " are Amicable Numbers." << endl;
} else {
cout << a << " and " << b << " are not Amicable Numbers." << endl;
}
return 0;
}
Output:
Hello Codeauri Family,Enter two numbers here if it is amicable number or not!:
220
284
220 and 284 are Amicable Numbers.
Pro-Tips💡
This program implements a function sumOfDivisors
to calculate the sum of divisors of a number.
The function loops through all numbers less than or equal to the square root of n
and checks if n
is divisible by the number.
If n
is divisible by the number, the number and n
divided by the number are added to the sum of divisors. The function returns the sum of divisors minus n
because n
is not a divisor of itself.
The areAmicableNumbers
function uses the sumOfDivisors
function to calculate the sum of divisors of a
and b
,
then returns true if the sum of divisors of a
is equal to b
and the sum of divisors of b
is equal to a
, indicating that a
and b
are Amicable Numbers.
The main
function prompts the user to enter two numbers and calls the areAmicableNumbers
function with the inputs.
If the function returns true, the numbers are Amicable Numbers and the program prints a message to that effect.
If the function returns false, the numbers are not Amicable Numbers and the program prints a message to that effect.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.