I have translated C++ code I wrote to Rust to do a Segmented Sieve of Zakiya (SSoZ).

(If you're interested -- The Segmented Sieve of Zakiya (SSoZ) | PDF | Prime Number | Central Processing Unit)

The Rust translation works perfectly on 64-bit Linux systems (over the number ranges I've tested so far). However, on 32-bit systems, the C++ works too but the same Rust code produces array index errors, which I suspect occurs due to casting errors converting from `u64`

values to `usize`

values.

I'm pretty sure the problem is exclusively in the following function.

```
fn segsieve(kn: usize,ki: u64,seg: &mut Vec<u8>,next: &mut Vec<usize>,primes: &Vec<usize>,pcnt: usize) -> usize {
// for Kn resgroups in segment
for b in 0..kn {seg[b] = 0;} // set every byte bit to prime (0)
for r in 0..RESCNT { // for each ith (of 8) residues for P5
let biti = 1 << r; // set the ith residue track bit mask
let row = r * pcnt; // set address to ith row in next[]
for j in 0..pcnt { // for each prime <= sqrt(N) for restrack
if (next[row+j] as u64) < (ki + (kn as u64)) {
let prime = primes[j];
let mut k = next[row+j];
if (k as u64) < ki {
k = ((ki - (k as u64)) % (prime as u64)) as usize;
if k != 0 {k = prime - k;}
} else {k -= ki as usize;}
while k < kn { // for each primenth byte < segment size
seg[k] |= biti; // set ith residue in byte as nonprime
k += prime;
}
}
}
}
// count the primes ('0' bits) in the segment for the Kn resgroup bytes
let mut primecnt: usize = 0;
for s in 0..kn {primecnt += PBITS[seg[s] as usize] as usize}
primecnt
}
```

The specific problems seems to be this section.

```
if (k as u64) < ki {
k = ((ki - (k as u64)) % (prime as u64)) as usize;
if k != 0 {k = prime - k;}
} else {k -= ki as usize;}
while k < kn { // for each primenth byte < segment size
seg[k] |= biti; // set ith residue in byte as nonprime
k += prime;
}
```

For some reason, as `ki`

hits a certain size, and when `k = 0`

for some `prime`

values, the compiler throws this panic:

```
thread '<main>' panicked at 'index out of bounds: the len is 262144 but the index is 4294967295', ../src/libcollections/vec.rs:1134
```

This is saying that the `u8`

array `seg[k]`

, which has a length of 262144 bytes, is being indexed with a value of `k = 2**32 - 1`

(or all bits are 1) . The math of the routine doesn't come close to allowing that to happen, but even when I mask off the k value like `k & 0x7ffffffff`

the error persists. So it seems `k`

is being set sometimes to all `1s`

instead of `0`

under certain conditions.

I've tried every trick I can think of to get around this problem (in Rust 1.6 and 1.7). I have even implemented another version to try to lesson indexing conflicts (which works on 64-bit distros too), which only causes the problem to show at different input values. I, thus, have concluded it must be an error in the 32-bit compiler, since it shows up the same on different 32-bit Linux systems I run in Virtualbox (VB).