Keith Number in C++

C++Server Side ProgrammingProgramming

In this tutorial, we are going to write a program that checks whether the given number is Keith Number or not.

The number n is called Keith number if it appears in the sequence generated using its digits. The sequence has first n terms as digits of the number n and other terms are recursively evaluated as sum of previous n terms.

Let's see the steps to solve the problem.

  • Initialise the number n.
  • Initialise an empty vector elements to store the sequence.
  • Count the digits and add every digit to the vecor.
  • Reverse the digits vector.
  • Initialise a variable with 0 called next element.
  • Write a loop that iterate till the next element is less than n.
    • Add the last n digits to get the next element.
    • Add the next element to the vector.
  • Return true if the next element is equal to n else false.


Let's see the code.

 Live Demo

using namespace std;
bool isKeithNumber(int n) {
   vector<int> elements;
   int temp = n, digitsCount = 0;
   while (temp > 0) {
      elements.push_back(temp % 10);
      temp = temp / 10;
   reverse(elements.begin(), elements.end());
   int nextElement = 0, i = digitsCount;
   while (nextElement < n) {
      nextElement = 0;
      for (int j = 1; j <= digitsCount; j++) {
         nextElement += elements[i - j];
   return nextElement == n;
int main() {
   isKeithNumber(43) ? cout << "Yes" << endl : cout << "No" << endl;
   isKeithNumber(14) ? cout << "Yes" << endl : cout << "No" << endl;
   isKeithNumber(197) ? cout << "Yes" << endl : cout << "No" << endl;
   return 0;


If you run the above code, then you will get the following result.



If you have any queries in the tutorial, mention them in the comment section.

Published on 09-Apr-2021 12:56:47