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



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.

Example

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;       k--;       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; }

Output

6 digit number with digital Root = 5 is : 500000
Updated on: 2020-01-27T06:26:20+05:30

131 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements