Skip to content

Instantly share code, notes, and snippets.

@rfaisal
Last active December 20, 2015 02:28
Show Gist options
  • Select an option

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

Select an option

Save rfaisal/6056065 to your computer and use it in GitHub Desktop.
There is one friendly number and N unfriendly numbers. We want to find how many numbers are there which exactly divide the friendly number, but does not divide any of the unfriendly numbers.
public class UnfriendlyNumbers {
private static long gcd(long a, long b){
if(b==0) return a;
else return gcd(b,a%b);
}
public static long calc(long[]arr, long k){
HashSet<Long> hs= new HashSet<Long>();
for(int i=0;i<arr.length;i++){
hs.add(gcd(arr[i],k));
}
int count=0;
long div1;
long div2;
boolean flag=false;
for(int i=1;i<=Math.sqrt(k);i++){
if(k%i==0){
div1=i;
div2=k/i;
for(long h:hs){
if(h%div1 == 0){
flag=true;
break;
}
}
if(flag==false) count++;
flag=false;
if(div1!=div2){
for(long h:hs){
if(h%div2 == 0){
flag=true;
break;
}
}
if(flag==false) count++;
flag=false;
}
}
}
return count;
}
public static void main(String[] args) throws FileNotFoundException {
Scanner in = new Scanner(System.in);
int n=in.nextInt();
long k=Long.parseLong(in.next());
long []arr= new long[n];
for(int i=0;i<n;i++){
arr[i]=Long.parseLong(in.next());
}
System.out.print(calc1(arr,k));
}
}
public class UnfriendlyNumbersTest {
@Test
public void testCalc() {
assertEquals(1, UnfriendlyNumbers.calc(new long[]{2, 5, 7, 4, 3, 8, 3, 18}, 16));
assertEquals(0, UnfriendlyNumbers.calc(new long[]{2, 4, 16}, 16));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment