Write a C program that reads 10 integers (between 0-1000) into a one-dimensional array
and computes and finds the value that has the largest chain. You should compute the
largest chain as explained below.
Example:
For each value (n) in your array, your chain will be determined as follows;
If n is even -> n=n/2
If n is odd -> n=3n+1
For example , if 12 is your starting number , the chain will be ,
6 -> 3 -> 10 -> 5 ->16 -> 8 -> 4 -> 2 -> 1
12 is even so 12/2 will be 6.
6 is even 6/3 will be 3.
3 is odd 3*3+1 will be 10.
.
.
.
The chain will grow until the value is 1.
Write a function called findLargestChain() that accepts an integer, finds and prints the
chain elements to the screen , and returns the number of elements.
You should store the number of elements into another array.
In the main program, you should read 10 integers into an array , call the function for each
integer and store the number of elements into another array.
1
Expert's answer
2018-03-27T08:04:05-0400
#include <stdio.h> #include <stdlib.h>
int findLargestChain(int n) { printf("Chain for %d\n",n); int ans=1; while(n>1) { if(n&1) { n=3*n+1; } else { n/=2; } ++ans; printf("%d",n); if(n!=1) { printf("->"); } }
printf("\n");
return ans; }
int main() { int *arr=malloc(sizeof(int)*10); int *resArr=malloc(sizeof(int)*10);
int i; int maxChainElement=0; int chainLength=0; for(i=0;i<10;++i) { arr[i]=rand()%1000; resArr[i]=findLargestChain(arr[i]); if(resArr[i]>chainLength) { chainLength=resArr[i]; maxChainElement=arr[i]; } }
printf("Element that has the largest chain with length %d is %d\n",chainLength,maxChainElement);
Comments
Leave a comment