arith.rs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 add_modular(params: &Params, a: u64, b: u64, c: usize) -> u64 {
  16. (a + b) % params.moduli[c]
  17. }
  18. pub fn invert_modular(params: &Params, a: u64, c: usize) -> u64 {
  19. params.moduli[c] - a
  20. }
  21. pub fn modular_reduce(params: &Params, x: u64, c: usize) -> u64 {
  22. (x) % params.moduli[c]
  23. }
  24. pub fn exponentiate_uint_mod(operand: u64, mut exponent: u64, modulus: u64) -> u64 {
  25. if exponent == 0 {
  26. return 1;
  27. }
  28. if exponent == 1 {
  29. return operand;
  30. }
  31. let mut power = operand;
  32. let mut product;
  33. let mut intermediate = 1u64;
  34. loop {
  35. if (exponent % 2) == 1 {
  36. product = multiply_uint_mod(power, intermediate, modulus);
  37. mem::swap(&mut product, &mut intermediate);
  38. }
  39. exponent >>= 1;
  40. if exponent == 0 {
  41. break;
  42. }
  43. product = multiply_uint_mod(power, power, modulus);
  44. mem::swap(&mut product, &mut power);
  45. }
  46. intermediate
  47. }
  48. pub fn reverse_bits(x: u64, bit_count: usize) -> u64 {
  49. if bit_count == 0 {
  50. return 0;
  51. }
  52. let r = x.reverse_bits();
  53. r >> (mem::size_of::<u64>() * 8 - bit_count)
  54. }
  55. pub fn div2_uint_mod(operand: u64, modulus: u64) -> u64 {
  56. if operand & 1 == 1 {
  57. let res = operand.overflowing_add(modulus);
  58. if res.1 {
  59. return (res.0 >> 1) | (1u64 << 63);
  60. } else {
  61. return res.0 >> 1;
  62. }
  63. } else {
  64. return operand >> 1;
  65. }
  66. }
  67. #[cfg(test)]
  68. mod test {
  69. use super::*;
  70. #[test]
  71. fn div2_uint_mod_correct() {
  72. assert_eq!(div2_uint_mod(3, 7), 5);
  73. }
  74. }