CodeChef June Contest: Finding Squares


Improve your writing skills in 5 minutes a day with the Daily Writing Tips email newsletter.

Our Chef is catering for a big corporate office party and is busy preparing different mouth watering dishes. The host has insisted that he serves his delicious cupcakes for dessert.
On the day of the party, the Chef was over-seeing all the food arrangements as well, ensuring that every item was in its designated position. The host was satisfied with everything except the cupcakes. He noticed they were arranged neatly in the shape of a rectangle. He asks the Chef to make it as square-like as possible.

The Chef is in no mood to waste his cupcakes by transforming it into a perfect square arrangement. Instead, to fool the host, he asks you to arrange the N cupcakes as a rectangle so that the difference between the length and the width is minimized.

Input

The first line of the input file contains an integer T, the number of test cases. Each of the following T lines contains a single integer N denoting the number of cupcakes.

Output

Output T lines, each indicating the minimum possible difference between the length and the width in a rectangular arrangement of the cupcakes.

Constraints

1 ≤ T ≤ 100
1 ≤ N ≤ 108

Input:
4
20
13
8
4

Output:
1
12
2
0

My Solution

#include <stdio.h>
#include <math.h>

int findSquare(int n){
  int factors[1000000] = {0};
  int i;
  int z = 0;
  int minDif = 100000000;
  int f1,f2;
  int temp;

  for (i=2;i<sqrt(n)+10;i++)
    if (n%i==0)
      factors[z++]=i;

  for (i=0;i<z;i++){
    f1 = factors[i];
    f2 = n/f1;
    if (f1>f2){
      temp = f1;
      f1 = f2;
      f2 = temp;
    }
    if (minDif>f2-f1){
      minDif = f2-f1;
    }
  }

  if (z==0)
    return n-1;
  return minDif;
}

int main(){
  int t,tt;
  int n;

  scanf("%d",&tt);

  for (t=0;t<tt;t++){
    scanf("%d",&n);
    if (t>0)
      printf("n");
    printf("%d",findSquare(n));
  }
  
  return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *