C++ code to find screen size with n pixels

C++Server Side ProgrammingProgramming

Suppose we have a number n. In a display there will be n pixels. We have to find the size of rectangular display. The rule is like below −

  • The number of rows (a) does not exceed number of columns (b) [a <= b]

  • The difference between b - a is as minimum as possible

So, if the input is like n = 12, then the output will be (3, 4)

Steps

To solve this, we will follow these steps −

i := square root of n
while n mod i is non-zero, do:
   (decrease i by 1)
return (i, n / i)

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
void solve(int n){
   int i = sqrt(n);
   while (n % i)
      i--;
   cout << i << ", " << n / i;
}
int main(){
   int n = 12;
   solve(n);
}

Input

12

Output

3, 4
raja
Updated on 30-Mar-2022 12:42:37

Advertisements