Amazon Interview Question
Backend DevelopersCountry: India
//============================================================================
// Name : MaximalCloseFactor.cpp
// Author : Nitish Raj, Scientist DRDO,raj.nitp@gmail.com
// Version :
// Copyright : Your copyright notice
// Description : MaximalCloset, Ansi-style
//============================================================================
#include <iostream>
using namespace std;
void findingMaximalCloset(int data, int &fac1 , int &fac2){
if(data == 1) return;
fac1 = 1;
fac2 = data;
bool flag = true;
while(flag)
{
fac1++;
if(fac1 == fac2) flag = false;
if(data%fac1 == 0)
{
fac2 = data/fac1;
if(fac1 == fac2) flag = false;
//cout<<"FAC 1 "<<fac1<<" FAC2 "<<fac2<<endl;
}
}
if(fac2 == 1){
data = data + 1;
fac1 = 1;
findingMaximalCloset(data,fac1,fac2);
}
else if(fac1 != 1 && fac2 != 1) return;
}
int main() {
int data,fac1 = 1,fac2 = 1;
cout << "Enter an integer for finding maximal close factor" << endl; // prints
cin>>data;
findingMaximalCloset(data,fac1 ,fac2);
cout<<"FACTORS ARE "<<fac1<<" * "<<fac2<<endl;
return 0;
}
Task is incorrect.
Probably it is required to find such I and B where B+I is minimum.
public class TestClass{
public static void main(String[] args) {
int n = 12;
int i = (int) Math.sqrt((double) n);
int b = (int) Math.round((double) n / (double) i);
System.out.println(n + ": " + i + "x" + b);
}
}
/**
* Created by arupdutta on 27/08/16.
* 1. get floored square root value of the number e.g. for 12 we get a value of 3
* 2. set the value in two variables, x = y = sqrt(num)
* 3. while x>=1 & y<=num check
* if x*y = num return x & y
* else if x*y <num increment y
* else decrement x
* 4. if loop break then return 1 and num
*/
import java.util.Scanner;
public class MaximumFactor {
public int[] getMaximalFactors(int num){
int[] factors = new int[2];
factors[0] = 1;
factors[1] = num;
int x, y;
x = y = (int)Math.sqrt(num);
while(x>=1 && y<=num){
int product = x * y;
if( product == num){
factors[0] = x;
factors[1] = y;
return factors;
} else if(product < num){
y++;
} else {
x--;
}
}
return factors;
}
public static void main(String[] args){
MaximumFactor m = new MaximumFactor();
Scanner s = new Scanner(System.in);
int[] factors = m.getMaximalFactors(s.nextInt());
System.out.println("Maximal factors: " + factors[0] + "\t" + factors[1]);
}
}
why not 4x3 for 13? 4x3=12 is closer to 13 than 5x3=15
- Anonymous July 30, 2016