Time for an 2014 update…

This commit is contained in:
Ingy döt Net 2014-01-17 05:32:22 +00:00
parent 372c577f83
commit 09687c4926
2520 changed files with 34227 additions and 7318 deletions

View file

@ -0,0 +1,42 @@
-module( parallel_calculations ).
-export( [fun_results/2, task/0] ).
fun_results( Fun, Datas ) ->
My_pid = erlang:self(),
Pids = [fun_spawn( Fun, X, My_pid ) || X <- Datas],
[fun_receive(X) || X <- Pids].
task() ->
Numbers = [12757923, 12878611, 12757923, 15808973, 15780709, 197622519],
Results = fun_results( fun factors/1, Numbers ),
Min_results = [lists:min(X) || X <- Results],
{_Max_min_factor, Number} = lists:max( lists:zip(Min_results, Numbers) ),
{Number, Factors} = lists:keyfind( Number, 1, lists:zip(Numbers, Results) ),
io:fwrite( "~p has largest minimal factor among its prime factors ~p~n", [Number, Factors] ).
factors(N) -> factors(N,2,[]).
factors(1,_,Acc) -> Acc;
factors(N,K,Acc) when N rem K == 0 -> factors(N div K,K, [K|Acc]);
factors(N,K,Acc) -> factors(N,K+1,Acc).
fun_receive( Pid ) ->
receive
{ok, Result, Pid} -> Result;
{Type, Error, Pid} -> erlang:Type( Error )
end.
fun_spawn( Fun, Data, My_pid ) ->
erlang:spawn( fun() ->
Result = try
{ok, Fun(Data), erlang:self()}
catch
Type:Error -> {Type, Error, erlang:self()}
end,
My_pid ! Result
end ).

View file

@ -1,8 +1,9 @@
import Control.Parallel.Strategies
mport Control.Parallel.Strategies
import Control.DeepSeq
import Data.List
import Data.Function
nums :: [Integer]
nums = [112272537195293
,112582718962171
,112272537095293
@ -10,21 +11,20 @@ nums = [112272537195293
,115797840077099
,1099726829285419]
factors :: Integral a => a -> [a]
factors n | n `rem` 2 == 0 = [2] ++ factors (n `quot` 2)
| otherwise = y
where y = [x | x <- [3,5..ceiling . sqrt $ fromIntegral n]
++ [n], n `rem` x == 0]
lowestFactor :: Integral a => a -> a -> a
lowestFactor s n | n `rem` 2 == 0 = 2
| otherwise = head $ y
where y = [x | x <- [s..ceiling . sqrt $ fromIntegral n]
++ [n], n `rem` x == 0, x `rem` 2 /= 0]
minPrimes :: [Integer] -> (Integer, [Integer])
minPrimes ns = (\(x, y) -> (x, y:factors ( x `quot` y))) $
maximumBy (compare `on` snd)
(zip ns (parMap rdeepseq (head . factors) ns))
primeFactors l n = f n l []
where f n l xs = if n > 1 then f (n `div` l) (lowestFactor (max l 3) (n `div` l)) (l:xs)
else xs
minPrimes ns = (\(x,y) -> (x,primeFactors y x)) $
maximumBy (compare `on` snd) $
zip ns (parMap rdeepseq (lowestFactor 3) ns)
main :: IO ()
main = do
putStrLn . concat $ ["The number with the "
, "largest minimum prime factor was:\n"
, show x, "\nWith factors: "]
mapM_ print y
where (x, y) = (minPrimes nums)
print $ minPrimes nums