Heres the idea Write a program that takes two integers, N and M, and find the largest integer composed of N-digits that is evenly divisible by M. N will always be 1 or greater, with M being 2 or greater. Note that some combinations of N and M will not have a solution. Example: if you are given an N of 3 and M of 2, the largest integer with 3-digits is 999, but the largest 3-digit number that is evenly divisible by 2 is 998, since 998 Modulo 2 is 0. Another example is where N is 2 and M is 101. Since the largest 2-digit integer is 99, and no integers between 1 and 99 are divisible by 101, there is no solution.
I would just like some tips on what to improve
#include <iostream>
#include <stdexcept>
#include <cmath>
using std::cin; using std::cout; using std::endl; using std::runtime_error;
using std::pow;
unsigned largestNumber(unsigned num1) {
return pow(10, num1) - 1;
}
void validNums(const int num1, const int num2) {
if (num1 < 1 || num1 > 9 || num2 < 2 || num2 > 999999999)
throw std::runtime_error("invalid input");
}
int divisbleBy(int num1, int num2) {
for (; num1 != 0; --num1) {
if (num1 % num2 == 0)
return num1;
}
return 0;
}
int main()
{
int num1 = 0, num2 = 0;
int answer = 0;
cout << "Enter 2 nums and we'll find biggest number possible with num1 digits and we'll then find closest number that num2 can divide by. Num1 has to be between 1-9 and num2 between 2-999-999-999" << endl;
cin >> num1 >> num2;
validNums(num1, num2);
if (answer = divisbleBy(largestNumber(num1), num2))
cout << "Largest number possible with " << num1 << " is " << largestNumber(num1) << " and the closest number to " << largestNumber(num1) << " divisible by " << num2 << " is " << answer << endl;
else
cout << "Invalid" << endl;
return 0;
}