Find numbers a and b that satisfy the given condition in C++

C++Server Side ProgrammingProgramming

Consider we have an integer n. Our task is to find two numbers a and b, where these three conditions will be satisfied.

  • a mod b = 0
  • a * b > n
  • a / b < n

If no pair is found, print -1.

For an example, if the number n = 10, then a and b can be a = 90, b = 10. This satisfies given rules.

To solve this problem, we will follow these steps −

  • Let b = n. a can be found using these three conditions
  • a mod b = 0 when a is multiple of b
  • a / b < n, so a / b = n – 1 which is < n
  • (a * b > n) => a = n

Example

#include<iostream>
using namespace std;
void findAandB(int n) {
   int b = n;
   int a = b * (n - 1);
   if (a * b > n && a / b < n) {
      cout << "a: " << a << endl;
      cout << "b: " << b;
   }else
      cout << -1 << endl;
   }
int main() {
   int n = 10;
   findAandB(n);
}

Output

a: 90
b: 10
raja
Published on 01-Nov-2019 15:05:58
Advertisements