Skip to content

Instantly share code, notes, and snippets.

@ofx ofx/collatz.cpp
Last active Mar 29, 2018

Embed
What would you like to do?
Collatz Conjecture
#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
You can’t perform that action at this time.