TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
check_amicable_pair.cpp
Go to the documentation of this file.
1
17#include <cassert>
18#include <iostream>
19
24namespace math {
31int sum_of_divisor(int num) {
32 // Variable to store the sum of all proper divisors.
33 int sum = 1;
34 // Below loop condition helps to reduce Time complexity by a factor of
35 // square root of the number.
36 for (int div = 2; div * div <= num; ++div) {
37 // Check 'div' is divisor of 'num'.
38 if (num % div == 0) {
39 // If both divisor are same, add once to 'sum'
40 if (div == (num / div)) {
41 sum += div;
42 } else {
43 // If both divisor are not the same, add both to 'sum'.
44 sum += (div + (num / div));
45 }
46 }
47 }
48 return sum;
49}
50
58bool are_amicable(int x, int y) {
59 return (sum_of_divisor(x) == y) && (sum_of_divisor(y) == x);
60}
61} // namespace math
62
67static void tests() {
68 assert(math::are_amicable(220, 284) == true);
69 assert(math::are_amicable(6368, 6232) == true);
70 assert(math::are_amicable(458, 232) == false);
71 assert(math::are_amicable(17296, 18416) == true);
72 assert(math::are_amicable(18416, 17296) == true);
73
74 std::cout << "All tests have successfully passed!" << std::endl;
75}
76
81int main() {
82 tests(); // perform self-tests implementations
83 return 0;
84}
static void tests()
Self-test implementations.
int main()
Main function.
for assert
bool are_amicable(int x, int y)
Function to check whether the pair is amicable or not.
int sum_of_divisor(int num)
Function to calculate the sum of all the proper divisor of an integer.