1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Erlangで素数と素数でないものを分けてリストを返す

1
Posted at

Erlangの修行中。erlangで特定の数字を入れると、素数と合成数で分けて、それぞれが入ったlistを返すというものを作った。

Source

- module(primenum).
- export([primenum/1, printnum/2]).

primenum(Num) when Num >= 2 ->
        primecheck(2, Num);
primenum(_Others) ->
        false.

primecheck(TargetNum, TargetNum) ->
        true;
primecheck(Num, TargetNum) when TargetNum rem Num =:= 0 ->
        false;
primecheck(Num, TargetNum) ->
        primecheck(Num+1, TargetNum).


createlist(Num, List) when Num == 0 ->
        List;
createlist(Num, List) ->
        createlist(Num-1 ,[Num | List]).


printnum(Num, Type) when Type =:= "Prime" ->
        List = createlist(Num, []),
        PrimeNum = lists:filter(fun(X) -> primenum(X) end, List);
printnum(Num, Type) when Type =:= "Composit" ->
        List = createlist(Num, []),
        PrimeNum = lists:filter(fun(X) -> primenum(X) end, List),
        CompositNum = List -- PrimeNum.

実行結果

2> primenum:printnum(100, "Prime").
[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,
 79,83,89,97]
3> primenum:printnum(100, "Composit").
[1,4,6,8,9,10,12,14,15,16,18,20,21,22,24,25,26,27,28,30,32,
 33,34,35,36,38,39,40,42|...]
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?