Prime number
Dennis
dkorpel at gmail.com
Thu Aug 2 09:25:57 UTC 2018
On Thursday, 2 August 2018 at 08:30:05 UTC, Greatsam4sure wrote:
> I know D is very powerful from my little experience. What is
> the idiomatic way to get prime numbers say from 1-30 without
> using loops(outer and inner loop). Can map, filter, fold etc in
> algorithm be use. Pls show some code with chain call.
>
> I can easily achieve even numberd and odd numbers using filter.
> But prime numbers I have to use 2loops.
>
> I will appreciate any help,just a newbie in D
If you just want a small number of prime numbers and your goal is
to make it a simple chain of range functions, I would do this:
```
import std.stdio: writeln;
import std.algorithm: filter, canFind;
import std.range: iota;
void main()
{
auto isPrime = (int number) => number >= 2 && !iota(2,
number).canFind!(x => (number % x) == 0);
writeln(iota(30).filter!isPrime);
}
```
You first make a simple prime filter, and then apply it to a
range of integers 0 to 30 using `iota(30)`.
I use lambda syntax for isPrime, but you can also make it an
explicit function:
```
bool isPrime(int number) {
return number >= 2 && !iota(2, number).canFind!(x => (number %
x) == 0);
}
```
`iota(2, number)` generates a range of integers from 2 to
`number` (excluding `number` itself), and with canFind we can see
if any of those divide our number. If so, then number isn't prime.
Note that if you're serious about calculating primes, you should
look for an efficient algorithm. Even in this naive algorithm
there are many optimization possibilities, like stopping the iota
at sqrt(number), but it would make the range code more
complicated.
More information about the Digitalmars-d-learn
mailing list