I'm trying to write a function that accepts a vector of integers as a parameter and returns the number of friendly pairs that can be found in that vector. The function must not use any other auxiliary functions.
A pair of numbers is friendly if the sum of all divisors of one number (not counting itself) is equal to another number and vice versa.
#include <iostream>
#include <vector>
int Number_Of_Friendly_Pairs(std::vector<int>a) {
std::vector<int>b;
for (int i = 0; i < a.size(); i ) {
int sum_of_divisors = 0;
for (int j = 1; j < a[i]; j )
if (a[i] % j == 0)
sum_of_divisors = j;
b.push_back(sum_of_divisors);
}
int number = 0;
for (int i = 0; i < a.size(); i )
for (int j = i 1; j < b.size(); j )
if (a[i] == b[j])
number ;
return number;
}
int main()
{
std::vector<int>b{220, 1184, 284, 1210, 2620, 2924};
std::cout << Number_Of_Friendly_Pairs(b);
return 0;
}
Is my code completely accurate? For vector {220, 1184, 284, 1210, 2620, 2924} it gives correct output (which is 3). However, I'm not sure will it give correct output for every case.
CodePudding user response:
A pair of numbers is friendly if the sum of all divisors of one number (not counting itself) is equal to another number and vice versa.
However, the code only tests that some sum of divisors equal to some number. The vice versa part is sorely missing. For example, the code claims one friendly pair in {7, 8}
.
You need to test for (a[i] == b[j]) && (b[i] == a[j])
.