ที่นี่เราจะดูวิธีสร้างตัวเลข A โดยเพิ่ม N หลัก และขณะเพิ่มหลักใหม่ในแต่ละขั้นตอน จะต้องหารด้วยอีกจำนวน B ลงตัว สมมติเราจะสร้างเลข 5 หลักโดยเพิ่ม 4 หลักพิเศษ เราจะตรวจสอบการหารด้วย 7 ตัวเลขจะเริ่มจาก 8 ตอนแรกจะต่อ 4 เข้าไป ตัวเลขจะเป็น 84 ซึ่งหารด้วย 7 ลงตัว จากนั้นเพิ่ม 0 เข้าไป ตัวเลขยังคงหารด้วย 7 ลงตัว หากสร้างตัวเลขไม่ได้ จะคืนค่า -1
อัลกอริทึม
addNDigits(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;
}
int 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