Skip to content

Instantly share code, notes, and snippets.

@chyanurag
Created July 21, 2025 10:58
Show Gist options
  • Save chyanurag/ea519fe09819e773f2c00dbfd0d20876 to your computer and use it in GitHub Desktop.
Save chyanurag/ea519fe09819e773f2c00dbfd0d20876 to your computer and use it in GitHub Desktop.
Collatz conjecture using only c++ templates
#include <iostream>
template <int N>
struct collatz;
template <>
struct collatz<1> {
static const int ans = 1;
};
template <int N>
struct collatz_even {
static const int ans = 1 + collatz<N/2>::ans;
};
template <int N>
struct collatz_odd {
static const int ans = 1 + collatz<3*N+1>::ans;
};
template <int N, bool is_even>
struct checker;
template <int N>
struct checker<N, true> {
static const int ans = collatz_even<N>::ans;
};
template <int N>
struct checker<N, false> {
static const int ans = collatz_odd<N>::ans;
};
template <int N>
struct collatz {
static const int ans = checker<N, (N%2 == 0)>::ans;
};
int main() {
std::cout << collatz<50>::ans << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment