Created
October 31, 2019 00:33
-
-
Save theimpostor/32cdfd45ef566f8c0ef40db439fb495c to your computer and use it in GitHub Desktop.
Solution to nine digits puzzle at compile time
This file contains hidden or 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 <stdio.h> | |
#define SWAP_INT(x, y) \ | |
do { \ | |
int tmp = (x); \ | |
(x) = (y); \ | |
(y) = tmp; \ | |
} while (0) | |
template <int N> struct ConstArray { | |
constexpr ConstArray() : arr() { | |
for (auto i = 0; i < N; i++) { | |
arr[i] = i + 1; | |
} | |
} | |
int arr[N]; | |
}; | |
constexpr int polydiv(int v, int d, ConstArray<9> n) { | |
int s = d - 1; | |
for (int i = s; i < 9; i++) { | |
SWAP_INT(n.arr[s], n.arr[i]); | |
int t = (v * 10) + n.arr[s]; | |
if (t % d == 0) { | |
if (d == 9) { | |
return t; | |
} | |
if ((t = polydiv(t, d + 1, n)) != 0) { | |
return t; | |
} | |
// continue | |
} | |
SWAP_INT(n.arr[d - 1], n.arr[i]); | |
} | |
return 0; | |
} | |
constexpr auto n = ConstArray<9>(); | |
constexpr auto p = polydiv(0, 1, n); | |
int main() { | |
printf("%d\n", p); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment