यहां हम देखेंगे कि एन अंकों को जोड़कर एक संख्या ए कैसे उत्पन्न की जाती है, और प्रत्येक चरण में नए अंक जोड़ते समय यह दूसरी संख्या बी से विभाज्य हो जाएगा। आइए विचार करें कि हम 4 जोड़कर 5 अंकों की संख्या बनाने जा रहे हैं। इसके साथ अतिरिक्त अंक। हम 7 से विभाज्यता की जांच करेंगे। संख्या 8 से शुरू होगी। तो पहले यह इसके साथ 4 जोड़ देगा, इसलिए संख्या 84 होगी, जो कि 7 से विभाज्य है। फिर संख्या के साथ 0 जोड़ें ताकि यह विभाज्य रहे। 7. अगर नंबर जनरेट नहीं किया जा सकता है, तो यह -1 वापस आ जाएगा।
एल्गोरिदम
NDigits जोड़ें(a, b, n)
begin num := a for all number x from 0 to 9, do temp := a * 10 + x if temp mod b is 0, then a := temp break end if done if num = a, then return -1 end if add remaining 0’s with a return a. end
उदाहरण
#include<iostream>
using namespace std;
int add_n_digits(int a, int b, int n) {
int num = a;
for (int i = 0; i <= 9; i++) { //test by adding all digits (0-9)
int tmp = a * 10 + i;
if (tmp % b == 0) {
a = tmp; //update a after adding
break;
}
}
if (num == a) //if no digit is added, return -1
return -1;
for (int j = 0; j < n - 1; j++) //after getting divisible number, add 0s
a *= 10;
return a;
}
main() {
int a, b, n;
cout << "Enter A, B and N: ";
cin >> a >> b >> n;
int res = add_n_digits(a, b, n);
if(res == -1) {
cout << "Unable to get this type of number";
} else {
cout << "Result is " << res;
}
} आउटपुट
Enter A, B and N: 8 7 4 Result is 84000
आउटपुट
Enter A, B and N: 10 11 5 Unable to get this type of number