-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprob32.cpp
48 lines (38 loc) · 1.09 KB
/
prob32.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <cmath>
#include <set>
#include <numeric>
#include <iostream>
#include <algorithm>
using namespace std;
int nums[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
template <class InputIterator>
inline int calc_val(InputIterator first, InputIterator last)
{
int res = 0;
while (first != last) {
res += *first * pow(10, distance(first, last) - 1);
first++;
}
return res;
}
inline int IsProduct(int digA, int digB)
{
int multiplicand = calc_val(nums, nums + digA);
int multiplier = calc_val(nums + digA, nums + digA + digB);
int prod_expected = calc_val(nums + digA + digB, nums + 9);
return (prod_expected == multiplicand * multiplier) ? prod_expected : 0;
}
int main()
{
set<int> products;
int res;
do {
if (res = IsProduct(4, 1)) products.insert(res);
} while (next_permutation(nums, nums + 9));
sort(nums, nums + 9);
do {
if (res = IsProduct(3, 2)) products.insert(res);
} while (next_permutation(nums, nums + 9));
cout << accumulate(products.begin(), products.end(), 0) << endl;
return 0;
}