-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprime.service.ts
40 lines (37 loc) · 1.01 KB
/
prime.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import { Injectable, Logger } from '@nestjs/common';
/**
* The prime service allows you to compute prime numbers.
*/
@Injectable()
export class PrimeService {
/**
* PrimeService Logger
*/
private readonly logger = new Logger(PrimeService.name);
/**
* Compute prime numbers up to the limit.
* @param limit limit of the prime numbers to compute
* @returns A list of prime numbers up to the limit
*/
public computePrimeNumber(limit: number): number[] {
this.logger.log({ message: 'Computing prime number...', limit });
const primesBoolean: boolean[] = [];
for (let i = 2; i <= limit + 1; i++) {
primesBoolean.push(true);
}
for (let i = 2; i <= Math.sqrt(limit); i++) {
if (primesBoolean[i]) {
for (let j = i * i; j < limit; j += i) {
primesBoolean[j] = false;
}
}
}
const primes: number[] = [];
primesBoolean.forEach((value, index) => {
if (value) {
primes.push(index);
}
});
return primes.slice(2);
}
}