In this tutorial, we will write a Keith number in C++. It is one of the most asked questions in an interview. Before that, you may go through the following topic in C programming.
What is Keith Number?
A positive n digit number x is called a Keith number or repfigit number (repetitive Fibonacci-like digit) if it is arranged in a special number sequence generated using its digits. This sequence has n terms as digit of x and the next term is determined by the sum of previous n terms and so on. And if the number x falls under this sequence then x is a Keith Number. Example: 19, 742, etc
Explanation: Consider the number 742. Go through the following steps:
First separate the digit, 7, 4, 2.
To find the next term, add the digits, 7+4+2 = 13
New Series: 7, 4, 2, 13.
To find the next term, add the last three digits of the above sequence, 13+2+4=19
New Series: 7, 4, 2, 13, 19.
To find the next term, add the last three digits of the above sequence, 19+13+2=34
New Series: 7, 4, 2, 13, 19, 34.
To find the next term, add the last three digits of the above sequence, 34+19+13=66
New Series: 7, 4, 2, 13, 19, 34, 66.
To find the next term, add the last three digits of the above sequence, 66+34+19=119
New Series: 7, 4, 2, 13, 19, 34, 66, 119.
To find the next term, add the last three digits of the above sequence, 119+66+34=219
New Series: 7, 4, 2, 13, 19, 34, 66, 119, 219.
To find the next term, add the last three digits of the above sequence, 219+119+66=404
New Series: 7, 4, 2, 13, 19, 34, 66, 119, 219, 404.
To find the next term, add the last three digits of the above sequence, 404+219+119=742
New Series: 7, 4, 2, 13, 19, 34, 66, 119, 219, 404, 742.
Now we will stop as we got the number 742 as the term of the series. Hence 742 is a Keith Number.
C++ Program to check whether the Number is Keith Number or not
#include <bits/stdc++.h>
using namespace std;
int digitCount(int n)
{
int counter = 0;
while (n > 0)
{
n = n / 10;
counter++;
}
return counter;
}
int main()
{
int num1 = 0, arr1[10], temp = 0, flag = 0, i = 0, sum = 0;
cout << "Enter a number: ";
cin >> num1;
temp = num1;
for (i = digitCount(temp) - 1; i >= 0; i--)
{
arr1[i] = num1 % 10;
num1 /= 10;
}
while (flag == 0)
{
for (i = 0; i < digitCount(temp); i++)
sum += arr1[i];
if (sum == temp)
{
cout << "The entered number is a Keith Number\n";
flag = 1;
}
if (sum > temp)
{
cout << "The entered number is NOT a Keith Number\n";
flag = 1;
}
for (i = 0; i < digitCount(temp); i++)
{
if (i != digitCount(temp) - 1)
arr1[i] = arr1[i + 1];
else
arr1[i] = sum;
}
sum = 0;
}
}
Output:
//Run 1
Enter a number: 197
The entered number is a Keith Number
//Run 2
Enter a number: 15
The entered number is NOT a Keith number