In: Computer Science
in C programming
Assume that we have a series that is find as follows:
K1=1
K2=2
K3=3
K4=K1+K2+K3
...
K(n) = K (n-1) + K(n-2) + K(n-3)
Here is the sequence:
1, 2, 3, 6, 11, 20, 37, ...
Write a code to print the Kth number in this sequence (not greater than 50) that is collected from the input (user will input a number smaller or equal to 50 and the program produce the entry in the series for that number).
Ex:
Inter an integer less than 50: 6
Output: 20
Please look at my code and in case of indentation issues check the screenshots.
------------main.c----------------
#include <stdio.h>
int main()
{
int k;
long int k1 = 1, k2 = 2, k3 = 3;
//initialize first 3 numbers of the series
printf("Enter an integer less than 50: ");
scanf("%d", &k);
//read the
value of k
long int kthNumber;
//we have
to find kth number
if(k == 1)
//if k == 1, kth number is
k1
kthNumber = k1;
else if(k == 2)
//if k == 2, kth number is k2
kthNumber = k2;
else if(k == 3)
//if k == 3, kth number is k3
kthNumber = k3;
else if (k > 3){
long int temp;
for(int i = 4; i <= k;
i++){ //loop from i = 4 to k
temp = k1 + k2 +
k3; //keep adding previous three
numbers
k1 =
k2;
// (k1, k2, k3) ---> (k2,
k3, k1+k2+k3)
k2 = k3;
k3 = temp;
}
kthNumber = k3;
//kth number will be in k3
}
printf("Output: %ld\n", kthNumber);
//print output
return 0;
}
--------------Screenshots-------------------
----------------------Output------------------------------------
-----------------------------------------------------------------------------------------------------------------
Note: We have used long int to store kth number, because for kthNumber is very large for k > 35, and int cannot hold all the digits. We need long int data type which can hold larger integers.
-----------------------------------------------------------------------------------------------------------------
Please give a thumbs up if you find this answer helpful.
If it doesn't help, please comment before giving a thumbs
down.
Please Do comment if you need any clarification.
I will surely help you.
Thankyou