@@ -34,7 +34,7 @@ public static int sqrt(int x) {
34
34
if (x < 0 )
35
35
throw new IllegalArgumentException ("Square root of negative number" );
36
36
int y = 0 ;
37
- for (int i = 32768 ; i != 0 ; i >>>= 1 ) {
37
+ for (int i = 1 << 15 ; i != 0 ; i >>>= 1 ) {
38
38
y |= i ;
39
39
if (y > 46340 || y * y > x )
40
40
y ^= i ;
@@ -109,19 +109,19 @@ public static int powMod(int x, int y, int m) {
109
109
110
110
// Exponentiation by squaring
111
111
int z = 1 ;
112
- while ( y != 0 ) {
112
+ for (; y != 0 ; y >>>= 1 ) {
113
113
if ((y & 1 ) != 0 )
114
114
z = (int )((long )z * x % m );
115
115
x = (int )((long )x * x % m );
116
- y >>>= 1 ;
117
116
}
118
117
return z ;
119
118
}
120
119
121
120
122
- // Returns x^-1 mod m, where the result is in the range [0, m). Note that (x * x^-1) mod m = (x^-1 * x) mod m = 1.
121
+ // Returns x^-1 mod m, where the result is in the range [0, m).
122
+ // Note that (x * x^-1) mod m = (x^-1 * x) mod m = 1.
123
123
public static int reciprocalMod (int x , int m ) {
124
- if (!(m > 0 && 0 <= x && x < m ))
124
+ if (!(0 <= x && x < m ))
125
125
throw new IllegalArgumentException ();
126
126
127
127
// Based on a simplification of the extended Euclidean algorithm
@@ -179,7 +179,7 @@ public static int gcd(int x, int y) {
179
179
}
180
180
181
181
182
- // Tests whether the given integer is prime.
182
+ // Tests whether the given non-negative integer is prime.
183
183
public static boolean isPrime (int x ) {
184
184
if (x < 0 )
185
185
throw new IllegalArgumentException ("Negative number" );
@@ -201,7 +201,8 @@ else if (x == 2)
201
201
202
202
// Returns a Boolean array 'isPrime' where isPrime[i] indicates whether i is prime, for 0 <= i <= n.
203
203
// For a large batch of queries, this is faster than calling isPrime() for each integer.
204
- // For example: listPrimality(100) = {false, false, true, true, false, true, false, true, false, false, ...} (array length 101).
204
+ // For example: listPrimality(100) = {false, false, true, true, false, true, false, true,
205
+ // false, false, false, true, false, true, false, false, false, true, ...} (array length 101).
205
206
public static boolean [] listPrimality (int n ) {
206
207
if (n < 0 )
207
208
throw new IllegalArgumentException ("Negative array size" );
@@ -243,7 +244,7 @@ public static int[] listPrimes(int n) {
243
244
}
244
245
245
246
246
- // Returns an array spf where spf[k] is the smallest prime factor of k, valid for 0 <= k <= n.
247
+ // Returns an array spf where spf[k] is the smallest prime factor of k, valid for 2 <= k <= n.
247
248
// For example: listSmallestPrimeFactors(10) = {0, 0, 2, 3, 2, 5, 2, 7, 2, 3, 2}.
248
249
public static int [] listSmallestPrimeFactors (int n ) {
249
250
int [] result = new int [n + 1 ];
0 commit comments