Erlang:打印第一个参数和第二个参数之间的素数列表

thtygnil  于 2022-12-08  发布在  Erlang
关注(0)|答案(5)|浏览(240)

I'm new to Erlang and just had a question. I've already looked here on StackOverflow and done a lot of Googling.
I'm trying to write a function that takes two parameters and returns the prime numbers between them. My biggest issue is with Prime testing (checking if a number is prime). I fix the rest of the stuff later.
Here's the code I have so far:
-module(ListPrime). -export([primeList/2]).
primeList(0, 0)-> io:format("No prime numbers here ~s~n", [0]);primeList(Start, Finish)-> CheckPrime = Finish rem Start, if Start =< Finish, CheckPrime == 1 -> primeList(Start, Finish-1) end.`
Basically what I'm trying to do is:

  • Check if Finish is a prime number.
  • If not, move on to the next number (Finish-1).
  • Continue until the base case has been reached.

It compiles but it obviously doesn't do what I want it to do because I don't know how to check if a number is prime.
I know what the definition of a Prime Number is (a number that is only divisible by itself and 1) but the only thing that comes to mind to write when I think about that definition is:
Finish rem Finish
and line of code works for any number that is used. How do I check if a number is prime in Erlang? Thank you very much.

jtw3ybtb

jtw3ybtb1#

下面的代码将测试一个数字是否是素数。只需调用函数isPrime,它就会返回true或false。

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

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

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

yruzcnhs2#

试试这个,我希望它能正常工作,只要调用函数prime,它就会返回falsetrue

divisors(N) ->
    [ X || X <- lists:seq(1,N), (N rem X)==0].
prime(N) when N == 0; N == 1 ->
    false;
prime(2) ->
    true;
prime(N) ->
    divisors(N) == [1,N].
up9lanfz

up9lanfz3#

试试这个:

prime([X|_]) when X =< 1 -> error(not_a_prime);
prime([X|Ns]) -> [N || N <- Ns, N rem X /= 0].
liwlm1x9

liwlm1x94#

你需要一个调用函数!就像这样做:

%% caller function
run(X, Y) ->
    prime(lists:seq(X, Y)).

%% prime function
prime([X|_]) when X =< 1 -> error(not_a_prime);
prime([X|Ns]) -> [N || N <- Ns, N rem X /= 0].

lists:seq(X, Y) :=创建两个数字之间的列表

xqk2d5yq

xqk2d5yq5#

这可能不是设置函数的最有效方法,但它很有效:

prime(2)->true;
prime(N)when N rem 2 =:= 0-> false;
prime(3)->true;
prime(Odd)->prime(Odd,3).

prime(N,I)when N rem I =:= 0->false;
prime(N,I)when I*I > N->true;
prime(N,I)->prime(N,I+2).

primes(Start,Finish)->[X|| X <- lists:seq(Start,Finish), prime(X)].

相关问题