Finding number of steps to reach 1 by given conditions.
/* The following iterative sequence is defined for the set of positive integers:
n → n/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
It can be seen that this sequence (starting at 13 and finishing at 1)
contains 10 terms
Although it has not been proved yet (Collatz Problem), it is thought that all starting
numbers finish at 1.
Which starting number, under one million, produces the longest chain?
NOTE: Once the chain starts the terms are allowed to go above one million.*/
#include <stdio.h>
#include <inttypes.h>
#include <stdlib.h>
#include <time.h>
#include <Windows.h>
// void max_count(int *arr, int range)
// {
// int max = range;
// for (range; range > 0; range--)
// {
// // printf("counts : %d\n", *(arr + range));
// if (*(arr + range) > *(arr+max))
// {
// max = range;
// }
// }
// free(arr);
// printf("Maximum chain number:%d\n", max);
// }
void collatz(uint32_t range)
{
int max=0;
uint32_t *num_count = (uint32_t *)calloc(range, sizeof(int));
*(num_count) = 0;
for (uint32_t i = 1; i <= range; i++)
{
int count = 1;
uint32_t num = i;
while (num != 1)
{
// printf("%d ->", num);
if (num < i)
{
count += *(num_count + num)-1;
break;
}
if (num%2 == 0)
{
num = num / 2;
}else{
num = 3 * num + 1;
}
count++;
}
// printf("1\n");
*(num_count + i) = count;
if (*(num_count + i) > *(num_count+max))
{
max = i;
}
}
free(num_count);
printf("Maximum chain number:%d\n", max);
}
int main(int argc, char const *argv[])
{
//clock
// to store the execution time of code
double time_spent = 0.0;
clock_t begin = clock();
//function
collatz(1000000);
//sleep clock
Sleep(3);
clock_t end = clock();
// calculate elapsed time by finding difference (end - begin) and
// dividing the difference by CLOCKS_PER_SEC to convert to seconds
time_spent += (double)(end - begin) / CLOCKS_PER_SEC;
printf("The elapsed time is %f seconds", time_spent);
return 0;
}
No comments:
Post a Comment