행렬 계수 유형에 템플릿으로되어있는 선형 대수 코드를 개발 중입니다. 가능한 유형 중 하나는 모듈러 산술을 할 수있는 클래스 다음과 같이 순진하게 구현 그러나C++에서 모듈러 산술 연산 최적화
template<typename val_t> // `val_t` is an integer type
class Modular
{
val_t val_;
static val_t modulus_;
public:
Modular(const val_t& value) : val_(value) { };
static void global_set_modulus(const val_t& modulus) { modulus_ = modulus; };
Modular<val_t>& operator=(const Modular<val_t>& other) { val_ = other.val_; return *this; }
Modular<val_t>& operator+=(const Modular<val_t>& other) { val_ += other.val_; val_ %= modulus_; return *this; }
Modular<val_t>& operator-=(const Modular<val_t>& other) { val_ -= other.val_; val_ %= modulus_; return *this; }
Modular<val_t>& operator*=(const Modular<val_t>& other) { val_ *= other.val_; val_ %= modulus_; return *this; }
Modular<val_t>& operator/=(const Modular<val_t>& other) { val_ *= other.inverse().val_; val_ %= modulus_; return *this; }
friend Modular<val_t> operator+(const Modular<val_t>& a, const Modular<val_t>& b) { return Modular<val_t>((a.val_ + b.val_) % Modular<val_t>::modulus_); };
friend Modular<val_t> operator-(const Modular<val_t>& a, const Modular<val_t>& b) { return Modular<val_t>((a.val_ - b.val_) % Modular<val_t>::modulus_); };
// ...etc.
};
, 프로그램이 Modular<int>
계수로 실행될 때, 그것이 int
계수와 함께 실행하는 경우보다 몇 배 느린 .
최대 성능을 얻으려면 주문의 "모듈 형"클래스에서 변경해야 할 사항은 무엇입니까?
(((a.val_*b.val_) % modulus) + ((c.val_*d.val_ % modulus) % modulus) % modulus)
실행중인 프로그래밍 환경은 무엇입니까? 컴파일러 최적화를 설정 했습니까? – wallyk
오버플로를 방지하기 위해 곱하기 전에 감소를 수행하고자 할 수 있습니다. –
모듈러스가 2의 거듭 제곱 인 경우 "x % 모듈러스"대신 "x & (모듈러 -1)"을 사용할 수 있습니다. (-10 % 8은 -2이지만 -10 & (8-1)은 6) –