Integer
私は整数mod nをシミュレートするはずです。この質問の完全性のために必要とされるInteger::inverse()
、Integer::pow(int)
は、もありエラー:整数整数:: pow(int)の 'this'引数として 'const Integer'を渡すと修飾子が破棄されます
Integer::Integer(int x)
: m(x), n(0)
{
}
Integer::Integer(int x, int y)
: n(y), m(x)
{
// if this->n greater than 1
if (this->n > 1)
{
// mod this->m by this->n
this->m %= this->n;
// if this->m is negative
if (this->m < 0)
{
// add this->n to it
this->m += this->n;
}
}
}
::私はInteger::isQuadraticResidue() const
を実装するために行くときに私がいる
Integer Integer::inverse()
{
// Extended Euclidean Algorithm
int t = 0,
r = this->n,
newT = 1,
newR = this->m;
while (newR != 0)
{
int quotient = r/newR,
tCopy = t,
rCopy = r,
newTCopy = newT,
newRCopy = newR;
t = newT;
newT = tCopy - quotient * newTCopy;
r = newR;
newR = rCopy - quotient * newRCopy;
}
if (r > 1)
{
throw Integer(-1);
}
if (t < 0) t = t + this->n;
return Integer(t, this->n);
}
Integer Integer::squared()
{
return Integer(this->m * this->m, this->n);
}
Integer Integer::pow(int x)
{
// if x less than 0, return this->inverse().pow(-x)
if (x < 0) return this->inverse().pow(-x);
// if x is 0, return Integer(1)
if (x == 0) return Integer(1, this->n);
// if x is 1, return *this
if (x == 1) return *this;
// if x is 2, return this->squared()
if (x == 2) return this->squared();
// if x greater than 2
if (x > 2)
{
// if x is even
if (x % 2 == 0)
{
// return this->pow(x/2).squared()
return this->pow(x/2).squared();
}
// return this->pow(x/2).squared() * (*this)
return this->pow(x/2).squared() * (*this);
}
}
問題は次のようになります。したがって、それはのようなコンストラクタを持っています
bool Integer::isQuadraticResidue() const
{
// if this->n is zero
if (this->n == 0)
{
// this doesn't belong to Integers mod anything. check for perfect square instead
double baseSquareRoot = std::sqrt((double)this->m);
return (baseSquareRoot == (double)((int)baseSquareRoot));
}
// this is quadratic residue iff this->pow((this->n + 1)/2) == Integer(1, this->n)
return (this->pow((n + 1)/2).m == 1);
}
エラー:error: passing ‘const Integer’ as ‘this’ argument of ‘Integer Integer::pow(int)’ discards qualifiers
が発生します。私は最後にconst
と関係があると思う。何ですか?
EDIT:クラスのヘッダファイルは、次のようになります。
#ifndef INTEGER_H
#define INTEGER_H
#include <iostream>
class Integer
{
public:
Integer(int);
Integer(int, int);
// functions
Integer inverse();
Integer squared();
Integer pow(int);
bool isQuadraticResidue() const;
Integer sqrt();
private:
int m, n;
};
#endif
これを変更する必要はありません。戻り値は 'const_cast'です。ここでXY問題をやっていますか? –
その質問に答えるには、いいえ。 –
クラスインターフェイスを追加できますか? – Raindrop7