arith.rs 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. use crate::params::*;
  2. use std::mem;
  3. pub fn multiply_uint_mod(a: u64, b: u64, modulus: u64) -> u64 {
  4. (((a as u128) * (b as u128)) % (modulus as u128)) as u64
  5. }
  6. pub const fn log2(a: u64) -> u64 {
  7. std::mem::size_of::<u64>() as u64 * 8 - a.leading_zeros() as u64 - 1
  8. }
  9. pub fn multiply_modular(params: &Params, a: u64, b: u64, c: usize) -> u64 {
  10. (a * b) % params.moduli[c]
  11. }
  12. pub fn multiply_add_modular(params: &Params, a: u64, b: u64, x: u64, c: usize) -> u64 {
  13. (a * b + x) % params.moduli[c]
  14. }
  15. pub fn exponentiate_uint_mod(operand: u64, mut exponent: u64, modulus: u64) -> u64 {
  16. if exponent == 0 {
  17. return 1;
  18. }
  19. if exponent == 1 {
  20. return operand;
  21. }
  22. let mut power = operand;
  23. let mut product;
  24. let mut intermediate = 1u64;
  25. loop {
  26. if (exponent % 2) == 1 {
  27. product = multiply_uint_mod(power, intermediate, modulus);
  28. mem::swap(&mut product, &mut intermediate);
  29. }
  30. exponent >>= 1;
  31. if exponent == 0 {
  32. break;
  33. }
  34. product = multiply_uint_mod(power, power, modulus);
  35. mem::swap(&mut product, &mut power);
  36. }
  37. intermediate
  38. }
  39. pub fn reverse_bits(x: u64, bit_count: usize) -> u64 {
  40. if bit_count == 0 {
  41. return 0;
  42. }
  43. let r = x.reverse_bits();
  44. r >> (mem::size_of::<u64>() * 8 - bit_count)
  45. }
  46. pub fn div2_uint_mod(operand: u64, modulus: u64) -> u64 {
  47. if operand & 1 == 1 {
  48. let res = operand.overflowing_add(modulus);
  49. if res.1 {
  50. return (res.0 >> 1) | (1u64 << 63);
  51. } else {
  52. return res.0 >> 1;
  53. }
  54. } else {
  55. return operand >> 1;
  56. }
  57. }
  58. #[cfg(test)]
  59. mod test {
  60. use super::*;
  61. #[test]
  62. fn div2_uint_mod_correct() {
  63. assert_eq!(div2_uint_mod(3, 7), 5);
  64. }
  65. }