Created
May 10, 2013 09:00
-
-
Save tripped/5553312 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <set> | |
#include <utility> | |
#include <iostream> | |
#include <initializer_list> | |
#include <algorithm> | |
#include <math.h> | |
std::set<int> divisors(int n) | |
{ | |
std::set<int> divs; | |
divs.insert(1); | |
for (int i = 2; i < sqrt(n) + 1; ++i) | |
if (n % i == 0) | |
divs.insert({i, n/i}); | |
return divs; | |
} | |
int sumdiv(int n) | |
{ | |
const auto& divs = divisors(n); | |
return std::accumulate(divs.begin(), divs.end(), 0); | |
} | |
std::pair<int,int> apair(int x) | |
{ | |
int b = sumdiv(x); | |
return std::make_pair(std::min(x,b), std::max(x,b)); | |
} | |
bool haspair(int x) | |
{ | |
return (sumdiv(x) != x) && (sumdiv(sumdiv(x)) == x); | |
} | |
std::set<std::pair<int,int>> amicable_pairs(int count) | |
{ | |
int x = 1; | |
std::set<std::pair<int,int>> results; | |
while(1) | |
{ | |
if (haspair(x)) | |
results.insert(apair(x)); | |
if (results.size() >= count) | |
break; | |
++x; | |
} | |
return results; | |
} | |
int main() | |
{ | |
for (auto x: amicable_pairs(10)) | |
std::cout << "(" << x.first << ", " << x.second << "), "; | |
std::cout << "\n"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment