Last active
March 29, 2018 12:58
-
-
Save ofx/306d47f33e06374196c52cc1680ff8b3 to your computer and use it in GitHub Desktop.
Collatz Conjecture
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> | |
#include <ctime> | |
#include <tuple> | |
constexpr const std::tuple<unsigned long, unsigned long> max(const unsigned int a, const unsigned int b) | |
{ | |
const auto c = [](auto&& s, const unsigned long n) constexpr -> const unsigned int { | |
if (n == 1) return 1; | |
return 1 + s(s, n % 2 ? n * 3 + 1 : n / 2); | |
}; | |
std::tuple<unsigned long, unsigned long> t; | |
for (unsigned int i = a ; i <= b ; ++i) | |
{ | |
const auto s = c(c, i); | |
if (s > std::get<0>(t)) t = std::make_tuple(s, i); | |
} | |
return t; | |
} | |
int main() | |
{ | |
const unsigned int N = 1000000; | |
const auto a = std::clock(); | |
const auto M = max(1, N); | |
const auto d = std::clock() - a; | |
std::cout << "Time: " << d / (double)(CLOCKS_PER_SEC / 1000) << " ms" << std::endl; | |
std::cout << "Max: " << std::get<1>(M) << " (" << std::get<0>(M) << ")" << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment