Skip to content

Instantly share code, notes, and snippets.

@rfaisal
Created July 13, 2013 08:56
Show Gist options
  • Select an option

  • Save rfaisal/5990054 to your computer and use it in GitHub Desktop.

Select an option

Save rfaisal/5990054 to your computer and use it in GitHub Desktop.
You will be given some decimal digits in a int[] digits. Build an integer with the minimum possible number of factors, using each of the digits exactly once (be sure to count all factors, not only the prime factors). If more than one number has the same (minimum) number of factors, return the smallest one among them.
public class FewestFactors {
public static int number(int[] digits){
LinkedList<Integer> adapter= new LinkedList<Integer>();
for(int i=digits.length-1;i>=0;i--)
adapter.addFirst(digits[i]);
HashSet<LinkedList<Integer>> combinitions=combinate(adapter);
int min=Integer.MAX_VALUE;
int min_num=0;
for(LinkedList<Integer> c:combinitions){
int num=convertToInteger(c);
int factors=2;
for(int i=2;i<=num/2;i++){
if(num%i==0) factors++;
}
if(factors<min){
min=factors;
min_num=num;
}
else if(factors==min){
if(num<min_num) min_num=num;
}
}
return min_num;
}
private static HashSet<LinkedList<Integer>> combinate(LinkedList<Integer> input){
if(input.size()==1){
HashSet<LinkedList<Integer>> b=new HashSet<LinkedList<Integer>>();
b.add(input);
return b;
}
HashSet<LinkedList<Integer>>ret= new HashSet<LinkedList<Integer>>();
int len=input.size();
for(int i=0;i<len;i++){
Integer a = input.remove(i);
HashSet<LinkedList<Integer>>temp=combinate(new LinkedList<Integer>(input));
for(LinkedList<Integer> t:temp)
t.addFirst(a);
ret.addAll(temp);
input.add(i, a);
}
return ret;
}
private static int convertToInteger(LinkedList<Integer> input){
if(input.size()==0) return 0;
else{
int value=(int) Math.pow(10, input.size()-1);
value*=input.removeFirst();
return value+convertToInteger(input);
}
}
}
public class FewestFactorsTest {
@Test
public void testNumber() {
assertEquals(21, FewestFactors.number(new int[]{1,2}));
assertEquals(6, FewestFactors.number(new int[]{6, 0}));
assertEquals(447, FewestFactors.number(new int[]{4, 7, 4}));
assertEquals(1973, FewestFactors.number(new int[]{1, 3, 7, 9}));
assertEquals(1973, FewestFactors.number(new int[]{1, 3, 7, 9}));
assertEquals(241, FewestFactors.number(new int[]{1,2,4}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment