I am trying to run a quick primality test for Rust types u32 and u64 . As part of this, I need to calculate (n*n)%d , where n and d are u32 (or u64 , respectively).
While the result can easily fit into the data type, I donβt understand how to calculate it. As far as I know, there is no processor primitive for this.
For u32 we can fake it - drop it to u64 so that the product does not overflow, then we take the module, and then return it to u32 , knowing that it will not overflow. However, since I don't have the u128 data u128 (as far as I know), this trick will not work for u64 .
So, for u64 most obvious way I can come up with for this is to somehow calculate x*y to get a pair of (carry, product) of u64 , so we fix the number of overflows instead of just losing it (or panic or something else).
Is there any way to do this? Or another standard way to solve the problem?
source share