Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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,
#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
Advertisements