Created
May 13, 2018 04:45
-
-
Save seanpianka/431a5b4cce186fa0e295cb83d3948ec7 to your computer and use it in GitHub Desktop.
A C++ script written to generate sequences from the Collatz Conjecture, an open problem in mathematics.
This file contains 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 <fstream> | |
#include <cstdlib> | |
#include <ctime> | |
int main(int argc, char** argv) | |
{ | |
int time_initial = 0, | |
time_final = 0, | |
time_delta = 0; | |
long long int limit = 10000; | |
std::ofstream output; | |
output.open("collatz_sequences.txt"); | |
output << "**Collatz Conjecture Sequences**\n\n"; | |
if (argc != 2) | |
{ | |
std::cout << "Enter the number of sequences to generate: "; | |
for (;;) | |
{ | |
if (std::cin >> limit) { break; } | |
std::cout << "Invalid input, retry (enter another limit): "; | |
std::cin.sync(); | |
std::cin.clear(); | |
} | |
} | |
else | |
{ | |
if (atoi(argv[1]) > 0 && atoi(argv[1]) <= 100000000) | |
{ | |
limit = atoi(argv[1]); | |
} | |
} | |
time_initial = time(0); | |
for (int i = 2; i <= limit; i++) | |
{ | |
output << "** Number: " << i << " **\n\n"; | |
int sequence_num = i, sequence_length = 0; | |
char arrow[] = " -> "; | |
output << sequence_num << arrow; | |
for (int sequence_num = i; sequence_num != 1; sequence_length++) | |
{ | |
if (sequence_num % 2 == 0) | |
{ | |
sequence_num /= 2; | |
} | |
else | |
{ | |
sequence_num = ((sequence_num * 3) + 1); | |
} | |
if (sequence_num != 1) | |
{ | |
output << sequence_num << arrow; | |
} | |
} | |
output << "1\nCompleted in " << sequence_length << " steps.\n\n"; | |
} | |
time_final = time(0); | |
time_delta = time_final - time_initial; | |
output << "\n\n** Generating these sequences took " | |
<< time_delta | |
<< " seconds. **"; | |
output.close(); | |
std::cout << "Done.\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment