Given an integer N ≥ 1, the task is to find the smallest and the largest product of two N digit numbers.
Examples :
Input : N = 1 Output : Largest = 81 Smallest = 0 Explanation : Largest 1-digit number is 9 and 9 * 9 = 81 Smallest 1-digit number is 0 and 0 * 0 = 0 Input : N = 2 Output : Largest = 9801 Smallest = 100
Approach :
- For largest: The answer will be (10N – 1)2 because the series of product of two n digit numbers will go on like 9 * 9, 99 * 99, 999 * 999, …
- For smallest:
- If N = 1 then the answer will be 0.
- If N > 1 then the answer will be (10N – 1)2 because the series of product of two n digit numbers will go on like 0, 10*10, 100*100, …
Implementation :
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the smallest product
// of 2 n-digit numbers
int smallestProduct(int n)
{
if (n == 1)
return 0;
return pow( pow(10, n - 1), 2 );
}
// Function to return the largest product
// of 2 n-digit numbers
int largestProduct(int n)
{
return pow( (pow(10, n) - 1), 2);
}
// Driver code
int main()
{
int n = 2;
cout << "Largest = " << largestProduct(n) << endl;
cout << "Smallest = " << smallestProduct(n);
return 0;
}