Created
July 21, 2025 10:58
-
-
Save chyanurag/ea519fe09819e773f2c00dbfd0d20876 to your computer and use it in GitHub Desktop.
Collatz conjecture using only c++ templates
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 <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