red_herring
red_herring

Reputation: 11

Erlang: Function for determining Prime Numbers, True or False

So I'm new to Erlang. I have already Googled my question quite a few times.

I'm creating a function that is supposed to take a number (N) and return true if it is a Prime number and false if it is not. I've been thinking about it for the last couple of days (like I said, I'm new to Erlang) and have done some Googling. Here's the code I have so far:

 -module(isPrime).
 -export([isPrime/1]).

 isPrime(0)-> false;
 isPrime(1)-> false;
 isPrime(2)-> true;


 isPrime(N)->
  chPrime = N rem 2,
  if 
    chPrime = 1 -> false; %% illegal guard expression
    true->isPrime(N-1)
end.

It's not complete but I was just trying to run it to see how it would work but I keep getting:

isPrime.erl:11: illegal guard expression

I know if statements in Erlang have certain limitations that if statements in other programming languages do not (when I was Googling) but I'm not sure how else to write the if statement so N rem 2 is actually done.

Any suggestions as to how to rewrite my if statement to get N rem 2 working? Thank you very much.

Upvotes: 0

Views: 2889

Answers (2)

Reza Khaleghi
Reza Khaleghi

Reputation: 1

To complete the previous comment. This code will fix it for ya. After I debugged it, I realized that your if statement for chPrime must be 0 for saying false. Otherwise it will always say false. And a guide: variables in erlang must be defined with uppercase letter at start.

    ChPrime == 0 -> false;

If we want to use math here we can use this, too.

isPrime(N) -> isPrime(N,2).
isPrime(N,N) -> true;
isPrime(N,M)->
  ChPrime = N rem M,
  if 
    ChPrime == 0 -> false;
    true -> isPrime(N,M+1)
end.

Upvotes: 0

byaruhaf
byaruhaf

Reputation: 4743

The "=" is used for pattern matching or assignment you should use the comparisons operator "=="

isPrime(N)->
  chPrime = N rem 2,
  if
    chPrime == 1 -> false; %% fixes illegal guard expression
    true->isPrime(N-1)
end.

But "chPrime" is not a variable in erlang. All variables in erlang must start with and upper case letter.

isPrime(N)->
  ChPrime = N rem 2,
  if
    ChPrime == 1 -> false;
    ChPrime =:= 1 -> true
end.

i would rewrite the isPrime function like this using a case statement.

isPrime(N) ->
    case (N rem 2) =:= 0 of
        true -> true;
        _ -> false
    end.

The case statement allows you to use pattern matching and guards inside of a function clause while the if statement evaluates only a series of guards, without pattern matching.

You should use Recursion to repeat actions but is don't see any repeat actions if you just want to determine is a number is a prime number.

Upvotes: 1

Related Questions