Thursday, January 8, 2009

Erlang solution to Euler problem 3

Here is what I cooked up as a solution for project Euler problem number 3:

%% Author: cayle.spandon
%% Created: Jan 8, 2009
%% Description: Project Euler, problem 3
%%
%% The prime factors of 13195 are 5, 7, 13 and 29.
%%
%% What is the largest prime factor of the number 600851475143 ?

-module(euler3).

-export([solve/0, solve/1]).

solve() ->
solve(600851475143).

solve(N) ->
solve(N, 2).

solve(N, Try) ->
if
Try > N div 2 ->
N;
true->
if
N rem Try == 0 ->
solve(N div Try, Try);
true ->
solve(N, Try+1)
end
end.

2 comments:

Anonymous said...
This comment has been removed by the author.
Anonymous said...

%% My method is generalised for any numbers than a specific number

-module(prmno_multbl).
-author("qbuser").
-compile([export_all]).
%% API
-export([]).

%%to print all prime no.s
prime(L) when L==1 -> false;
prime(L) when L==2 -> true;
prime(L) when L>2 -> prime(L,2).

prime(L,Acc) when Acc prime(L,Acc+1);
prime(L,Acc) when Acc false;
prime(L,_) -> true.

prime_numbs(A)->[X||X<-lists:seq(1,A),prime(X)=/=false].
%%if we enter 10 list will be [2,3,5,7]


%%Largest prime factor
largest_primefactor(P)->lists:last([X||X<-prime_numbs(P)]).

%%printing all prime no.s and taking the last