Project Euler #3 in Erlang

I am trying to code Project Euler #3 in Erlang:

The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?

Here is my code:

-module(problem_3).
-compile(export_all).

start()->
    problem_3(600851475143, 2).

problem_3(Num, F) when Num > 1 ->
    case Num rem F of
    0 ->
        problem_3(Num / F, F);
    1 ->
        problem_3(Num, F + 1)
    end;

problem_3(Num, F) ->
    io:format("result: ~p~n", [F]).

But I have 2 problems with this code:

5> problem_3:start().
** exception error: no case clause matching 2
     in function  problem_3:problem_3/2

6> problem_3:problem_3(10, 2).
** exception error: bad argument in an arithmetic expression
     in function  problem_3:problem_3/2

Why I have this errors and how can I fix it?


The first error is pretty self-explanatory: If the remainder is greater than 1, no clause will match. Try changing the second clause to

_Else ->
         problem_3(Num, F+1)

which matches all cases where the remainder is not zero.

For the second error, I think it results from the expression Num / F . This yields a floating point number whereas problem_3 expects integer arguments. Try

problem_3(Num div F, F);

instead.


A few late pointers for speeding up the solution.

start()-> problem_3(600851475143, 3).

No need to check number 2.

Change

problem_3(Num, F + 1)

To

problem_3(Num, F + 2)

No reason to check even numbers.

链接地址: http://www.djcxy.com/p/80420.html

上一篇: 项目欧拉#1使用Haskell

下一篇: Erlang项目Euler#3