1/*
2 * Copyright (c) 2022-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16
17export class BitopsNSieveBits {
18  static primes(isPrime: int[], n1: int, n2: int): void {
19    let i: int;
20    let m: int = n2 << n1;
21    let size: int = m + 31 >> 5;
22
23    for (i = 0; i < size; i++) {
24      isPrime[i] = -1;
25    }
26
27    for (i = 2; i < m; i++) {
28      if ((isPrime[i >> 5] & 1 << (i & 31)) != 0) {
29        for (let j: int = i + i; j < m; j += i) {
30          isPrime[j >> 5] &= ~(1 << (j & 31));
31        }
32      }
33    }
34  }
35
36  private static sieve(n1: int, n2: int): int[] {
37    // Not parsed new int[...]
38    let isPrime: int[] = new int[(n2 << n1) + 31 >> 5];
39    BitopsNSieveBits.primes(isPrime, n1, n2);
40    return isPrime;
41  }
42
43  n1: int = 4;
44  n2: int = 10000;
45  static readonly expected: long = -1286749544853;
46
47  public run(): void {
48    let result: int[] = BitopsNSieveBits.sieve(this.n1, this.n2);
49    let sum: long = 0;
50    for (let i: int = 0; i < result.length; ++i) {
51      sum += result[i];
52    }
53
54    assert sum == BitopsNSieveBits.expected: "Incorrect result";
55  }
56}
57
58function main(): void {
59  let a = new BitopsNSieveBits;
60  a.run();
61}
62
63
64