github.com/ledgerwatch/erigon-lib@v1.0.0/pedersen_hash/fraction_field_element.h (about) 1 #ifndef STARKWARE_ALGEBRA_FRACTION_FIELD_ELEMENT_H_ 2 #define STARKWARE_ALGEBRA_FRACTION_FIELD_ELEMENT_H_ 3 4 #include "error_handling.h" 5 #include "prng.h" 6 7 namespace starkware { 8 9 /* 10 Represents a field element as an element of the fraction field of the original field. The elements 11 of the fraction field are a/b for a,b in the original field, and b != 0. The representation of 12 a FieldElementT b is b/1. Addition and multiplication for the fraction field are defined naturally 13 (see operator+ and operator*). The resulting field is isomorphic to the original field. This 14 fractional representation of the original field enables to perform an inverse cheaply: the inverse 15 of a/b is simply b/a. 16 */ 17 template <typename FieldElementT> 18 class FractionFieldElement { 19 public: 20 explicit constexpr FractionFieldElement(const FieldElementT& num_val) 21 : numerator_(num_val), denominator_(FieldElementT::One()) {} 22 23 /* 24 Creates a FractionFieldElement with the value num_val/denom_val. 25 denom_val can't be zero. 26 */ 27 constexpr FractionFieldElement(const FieldElementT& num_val, const FieldElementT& denom_val) 28 : numerator_(num_val), denominator_(denom_val) { 29 ASSERT(denominator_ != FieldElementT::Zero(), "Denominator can't be zero."); 30 } 31 32 FractionFieldElement operator+(const FractionFieldElement& rhs) const; 33 34 FractionFieldElement operator-(const FractionFieldElement& rhs) const; 35 36 FractionFieldElement operator-() const { return FractionFieldElement(-numerator_, denominator_); } 37 38 FractionFieldElement operator*(const FractionFieldElement& rhs) const; 39 FractionFieldElement operator/(const FractionFieldElement& rhs) const { 40 return *this * rhs.Inverse(); 41 } 42 43 bool operator==(const FractionFieldElement& rhs) const; 44 bool operator!=(const FractionFieldElement& rhs) const { return !(*this == rhs); } 45 46 FractionFieldElement Inverse() const; 47 48 static constexpr FractionFieldElement Zero() { 49 return FractionFieldElement(FieldElementT::Zero()); 50 } 51 52 static constexpr FractionFieldElement One() { return FractionFieldElement(FieldElementT::One()); } 53 54 /* 55 Returns a fraction field element: its numerator is a random FieldElementT generated by 56 FieldElementT::RandomElement of and its denominator is FieldElementT::One(). 57 */ 58 static FractionFieldElement RandomElement(Prng* prng) { 59 return FractionFieldElement(FieldElementT::RandomElement(prng)); 60 } 61 62 FieldElementT ToBaseFieldElement() const { return this->numerator_ * denominator_.Inverse(); } 63 64 explicit operator FieldElementT() const { return ToBaseFieldElement(); } 65 66 private: 67 FieldElementT numerator_; 68 FieldElementT denominator_; 69 }; 70 71 } // namespace starkware 72 73 #include "fraction_field_element.inl" 74 75 #endif // STARKWARE_ALGEBRA_FRACTION_FIELD_ELEMENT_H_