File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ const input = require ( 'fs' )
2+ . readFileSync ( process . platform === 'linux' ? '/dev/stdin' : './input.txt' )
3+ . toString ( )
4+ . trim ( )
5+ . split ( '\n' )
6+ . map ( ( el ) => el . split ( ' ' ) . map ( Number ) ) ;
7+
8+ const LIMIT = 1299709 ;
9+ const isPrime = Array ( LIMIT + 1 ) . fill ( true ) ;
10+ isPrime [ 0 ] = isPrime [ 1 ] = false ;
11+ const primes = [ ] ;
12+
13+ for ( let i = 2 ; i <= LIMIT ; i ++ ) {
14+ if ( isPrime [ i ] ) {
15+ primes . push ( i ) ;
16+ for ( let j = i * 2 ; j <= LIMIT ; j += i ) {
17+ isPrime [ j ] = false ;
18+ }
19+ }
20+ }
21+
22+ function solution ( input ) {
23+ const T = input [ 0 ] ;
24+ const list = input . slice ( 1 ) ;
25+ const result = [ ] ;
26+
27+ for ( let numb of list ) {
28+ if ( isPrime [ numb ] ) {
29+ result . push ( 0 ) ;
30+ continue ;
31+ }
32+
33+ let left = 0 ,
34+ right = primes . length - 1 ;
35+ while ( left < right ) {
36+ let mid = Math . floor ( ( left + right ) / 2 ) ;
37+ if ( primes [ mid ] >= numb ) right = mid ;
38+ else left = mid + 1 ;
39+ }
40+
41+ let prevPrime = primes [ left - 1 ] ;
42+ let nextPrime = primes [ left ] ;
43+
44+ result . push ( nextPrime - prevPrime ) ;
45+ }
46+ return result . join ( '\n' ) ;
47+ }
48+
49+ console . log ( solution ( input ) ) ;
You can’t perform that action at this time.
0 commit comments