I tried to solve the Unfriendly Number problem on InterviewStreet.
There is one friendly number, K, 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.
1 <= N <= 10^6
1 <= K <= 10^13
1 <= unfriendly numbers <= 10^18
Algorithm is quite simple:
- Find the set S. The set of gcd's of each unfriendly number with the friendly number.
- Find the set of divisors of the friendly number.
- Check if a divisor of the friendly number is a divisor of any element in S.
My code, where
u is the list of unfriendly numbers,
k is the friendly number.
nubOrd is the
O(n log n) time version of
test u k = length $ filter (not) $ map try divisors where try t = or $ map (t `divides` ) (nubOrd $ map (gcd k) u) divisors = concat [ [i,div k i] | i<-[1..floor $ sqrt $ fromIntegral k], i `divides` k] d `divides` n = n `mod` d == 0
This code exceeds the time limit. The Java version of this algorithm solves the problem fine. Are there any ways to improve this code or is Haskell too slow for solving this problem?