Print a number containing K digits with digital root D in C++

C++Server Side ProgrammingProgramming

In this problem, we are given two numbers K and D. Our task is to print a number of k digits and which has digital root equal to D.

Digital Root is a single-digit value which is the result of the recursive addition of the digits of the number till the one a single-digit number is reached. Also known as a digital sum.

Let’s take an example to understand the problem,

Input: D = 5 , K = 6
Output: 60000

To solve this problem, we will be using trials of zero’s after the number D. Our number will be {D000..(k-1 times)}. This is a simple and elegant solution to our problem which is also less complex.


Program to show the implementation of our solution,

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void printKdigitNumber(int k, int d) {
   if (d == 0 && k != 1)
      cout << "-1";
   else {
      cout << d;
      while (k--)
         cout << "0";
int main() {
   int K=6, D=5;
   cout<<K<<" digit number with digital Root = "<<D<<" is : ";
   printKdigitNumber(K, D);
   return 0;


6 digit number with digital Root = 5 is : 500000
Published on 27-Jan-2020 06:25:17