GFP2Element XTR_Exponentiate(const GFP2Element &b, const Integer &e, const Integer &p)
{
	unsigned int bitCount = e.BitCount();
	if (bitCount == 0)
		return GFP2Element(-3, -3);

	// find the lowest bit of e that is 1
	unsigned int lowest1bit;
	for (lowest1bit=0; e.GetBit(lowest1bit) == 0; lowest1bit++) {}

	GFP2_ONB<MontgomeryRepresentation> gfp2(p);
	GFP2Element c = gfp2.ConvertIn(b);
	GFP2Element cp = gfp2.PthPower(c);
	GFP2Element S[5] = {gfp2.ConvertIn(3), c, gfp2.SpecialOperation1(c)};

	// do all exponents bits except the lowest zeros starting from the top
	unsigned int i;
	for (i = e.BitCount() - 1; i>lowest1bit; i--)
	{
		if (e.GetBit(i))
		{
			gfp2.RaiseToPthPower(S[0]);
			gfp2.Accumulate(S[0], gfp2.SpecialOperation2(S[2], c, S[1]));
			S[1] = gfp2.SpecialOperation1(S[1]);
			S[2] = gfp2.SpecialOperation1(S[2]);
			S[0].swap(S[1]);
		}
		else
		{
			gfp2.RaiseToPthPower(S[2]);
			gfp2.Accumulate(S[2], gfp2.SpecialOperation2(S[0], cp, S[1]));
			S[1] = gfp2.SpecialOperation1(S[1]);
			S[0] = gfp2.SpecialOperation1(S[0]);
			S[2].swap(S[1]);
		}
	}

	// now do the lowest zeros
	while (i--)
		S[1] = gfp2.SpecialOperation1(S[1]);

	return gfp2.ConvertOut(S[1]);
}
Example #2
0
void InvertibleRSAFunction::Initialize(const Integer &n, const Integer &e, const Integer &d)
{
	if (n.IsEven() || e.IsEven() | d.IsEven())
		throw InvalidArgument("InvertibleRSAFunction: input is not a valid RSA private key");

	m_n = n;
	m_e = e;
	m_d = d;

	Integer r = --(d*e);
	unsigned int s = 0;
	while (r.IsEven())
	{
		r >>= 1;
		s++;
	}

	ModularArithmetic modn(n);
	for (Integer i = 2; ; ++i)
	{
		Integer a = modn.Exponentiate(i, r);
		if (a == 1)
			continue;
		Integer b;
		unsigned int j = 0;
		while (a != n-1)
		{
			b = modn.Square(a);
			if (b == 1)
			{
				m_p = GCD(a-1, n);
				m_q = n/m_p;
				m_dp = m_d % (m_p-1);
				m_dq = m_d % (m_q-1);
				m_u = m_q.InverseMod(m_p);
				return;
			}
			if (++j == s)
				throw InvalidArgument("InvertibleRSAFunction: input is not a valid RSA private key");
			a = b;
		}
	}
}
Example #3
0
Public Secp256k1PP::recover(Signature _signature, bytesConstRef _message)
{
	Public recovered;
	
	Integer r(_signature.data(), 32);
	Integer s(_signature.data()+32, 32);
	// cryptopp encodes sign of y as 0x02/0x03 instead of 0/1 or 27/28
	byte encodedpoint[33];
	encodedpoint[0] = _signature[64] | 2;
	memcpy(&encodedpoint[1], _signature.data(), 32);
	
	ECP::Element x;
	{
		m_curve.DecodePoint(x, encodedpoint, 33);
		if (!m_curve.VerifyPoint(x))
			return recovered;
	}
	
//	if (_signature[64] & 2)
//	{
//		r += m_q;
//		Guard l(x_params);
//		if (r >= m_params.GetMaxExponent())
//			return recovered;
//	}
	
	Integer z(_message.data(), 32);
	Integer rn = r.InverseMod(m_q);
	Integer u1 = m_q - (rn.Times(z)).Modulo(m_q);
	Integer u2 = (rn.Times(s)).Modulo(m_q);
	
	ECP::Point p;
	byte recoveredbytes[65];
	{
		// todo: make generator member
		p = m_curve.CascadeMultiply(u2, x, u1, m_params.GetSubgroupGenerator());
		if (p.identity)
			return Public();
		m_curve.EncodePoint(recoveredbytes, p, false);
	}
	memcpy(recovered.data(), &recoveredbytes[1], 64);
	return recovered;
}
Example #4
0
Integer MaurerProvablePrime(RandomNumberGenerator &rng, unsigned int bits)
{
	const unsigned smallPrimeBound = 29, c_opt=10;
	Integer p;

	unsigned int primeTableSize;
	const word16 * primeTable = GetPrimeTable(primeTableSize);

	if (bits < smallPrimeBound)
	{
		do
			p.Randomize(rng, Integer::Power2(bits-1), Integer::Power2(bits)-1, Integer::ANY, 1, 2);
		while (TrialDivision(p, 1 << ((bits+1)/2)));
	}
	else
	{
		const unsigned margin = bits > 50 ? 20 : (bits-10)/2;
		double relativeSize;
		do
			relativeSize = pow(2.0, double(rng.GenerateWord32())/0xffffffff - 1);
		while (bits * relativeSize >= bits - margin);

		Integer a,b;
		Integer q = MaurerProvablePrime(rng, unsigned(bits*relativeSize));
		Integer I = Integer::Power2(bits-2)/q;
		Integer I2 = I << 1;
		unsigned int trialDivisorBound = (unsigned int)STDMIN((unsigned long)primeTable[primeTableSize-1], (unsigned long)bits*bits/c_opt);
		bool success = false;
		while (!success)
		{
			p.Randomize(rng, I, I2, Integer::ANY);
			p *= q; p <<= 1; ++p;
			if (!TrialDivision(p, trialDivisorBound))
			{
				a.Randomize(rng, 2, p-1, Integer::ANY);
				b = a_exp_b_mod_c(a, (p-1)/q, p);
				success = (GCD(b-1, p) == 1) && (a_exp_b_mod_c(b, q, p) == 1);
			}
		}
	}
	return p;
}
Example #5
0
void input()
{
	printf( "n> " );
	string line;
	getline( cin, line );

	size_t comma = line.find( "," );
	cout << endl;

	chrono::time_point<chrono::steady_clock> start;
	chrono::time_point<chrono::steady_clock> end;

	if (comma == string::npos )	// single mode
	{
		int n = atoi( line.c_str() );
		if ( n < 0 ) return;

		start = chrono::high_resolution_clock::now();
		Integer f = fibonacci( n );
		end = chrono::high_resolution_clock::now();

		f.print( Fibonacci::getNumberPrefix( n ) );
		f.toFile( FILENAME );
	}
	else	// range mode
	{
		i64 b = atoll( line.substr( 0, comma ).c_str() );
		i64 e = atoll( line.substr( comma+1, line.length() ).c_str() );

		start = chrono::high_resolution_clock::now();
		fibonacci_range( b, e );
		end = chrono::high_resolution_clock::now();
	}

	if ( benchmark )
	{
		chrono::duration<i64, nano> time = end - start;
		printf( "mode: %s | time: %lli ms", mode.c_str(), time.count()/ 1000000);
	}
	cout << endl;
	input();
}
Example #6
0
Integer InvertibleRabinFunction::CalculateInverse(RandomNumberGenerator &rng, const Integer &in) const
{
	DoQuickSanityCheck();

	ModularArithmetic modn(m_n);
	Integer r(rng, Integer::One(), m_n - Integer::One());
	r = modn.Square(r);
	Integer r2 = modn.Square(r);
	Integer c = modn.Multiply(in, r2);		// blind

	Integer cp=c%m_p, cq=c%m_q;

	int jp = Jacobi(cp, m_p);
	int jq = Jacobi(cq, m_q);

	if (jq==-1)
	{
		cp = cp*EuclideanMultiplicativeInverse(m_r, m_p)%m_p;
		cq = cq*EuclideanMultiplicativeInverse(m_r, m_q)%m_q;
	}

	if (jp==-1)
	{
		cp = cp*EuclideanMultiplicativeInverse(m_s, m_p)%m_p;
		cq = cq*EuclideanMultiplicativeInverse(m_s, m_q)%m_q;
	}

	cp = ModularSquareRoot(cp, m_p);
	cq = ModularSquareRoot(cq, m_q);

	if (jp==-1)
		cp = m_p-cp;

	Integer out = CRT(cq, m_q, cp, m_p, m_u);

	out = modn.Divide(out, r);	// unblind

	if ((jq==-1 && out.IsEven()) || (jq==1 && out.IsOdd()))
		out = m_n-out;

	return out;
}
Example #7
0
File: main.cpp Project: riteme/test
int main() {
    initialize();

    tpow[0].store(1);
    for (int i = 1; i <= m; i++) {
        tpow[i] = tpow[i - 1];
        tpow[i] *= 2;
    }  // for

    Integer answer;

    for (int p = 1; p <= n; p++) {
        for (int i = 1; i <= m; i++) {
            f[i][i] = tpow[m];
            f[i][i] *= mat[p][i];
        }  // for

        for (int l = 1; l < m; l++) {
            for (int i = 1; i <= m; i++) {
                int j = i + l;
                int selected = i - 1 + m - j + 1;
                Integer t1 = tpow[selected];
                Integer t2 = tpow[selected];
                t1 *= mat[p][i];
                t1 += f[i + 1][j];
                t2 *= mat[p][j];
                t2 += f[i][j - 1];

                if (t1 < t2)
                    f[i][j] = t2;
                else
                    f[i][j] = t1;
            }  // for
        }      // for

        answer += f[1][m];
    }  // for

    answer.print();

    return 0;
}  // function main
Example #8
0
void gcd_ext(const Ptr<RCP<const Integer>> &g, const Ptr<RCP<const Integer>> &s,
             const Ptr<RCP<const Integer>> &t, const Integer &a, const Integer &b)
{
    mpz_t g_t;
    mpz_t s_t;
    mpz_t t_t;

    mpz_init(g_t);
    mpz_init(s_t);
    mpz_init(t_t);

    mpz_gcdext(g_t, s_t, t_t, a.as_mpz().get_mpz_t(), b.as_mpz().get_mpz_t());
    *g = integer(mpz_class(g_t));
    *s = integer(mpz_class(s_t));
    *t = integer(mpz_class(t_t));

    mpz_clear(g_t);
    mpz_clear(s_t);
    mpz_clear(t_t);
}
Example #9
0
// a and b are positive and a > b
void Integer::subtract(Integer& a, Integer& b, Integer& c) const
{
    int n, borrow = 0;
    unsigned int i;

    for (i = 0; i < a.size(); i++) {
        n = a[i] - b[i] - borrow;

        if (n < 0) {
            n += BASE;
        }

        borrow = (n < 0) ? 1 : 0;
        c[i] = n;
    }

    c.set_size(i);
    c.adjust();
    c.set_sign(PLUS);
}
Example #10
0
void SubsetSlow(Thread& thread, Value const& a, Value const& i, Value& out) {
	if(i.isDouble() || i.isInteger()) {
		Integer index = As<Integer>(thread, i);
		int64_t positive = 0, negative = 0;
		for(int64_t i = 0; i < index.length(); i++) {
			if(index[i] > 0 || Integer::isNA(index[i])) positive++;
			else if(index[i] < 0) negative++;
		}
		if(positive > 0 && negative > 0)
			_error("mixed subscripts not allowed");
		else if(positive > 0) {
			switch(a.type()) {
				case Type::Null: out = Null::Singleton(); break;
#define CASE(Name,...) case Type::Name: SubsetInclude<Name>::eval(thread, (Name const&)a, index, positive, out); break;
						 VECTOR_TYPES_NOT_NULL(CASE)
#undef CASE
				default: _error(std::string("NYI: Subset of ") + Type::toString(a.type())); break;
			};
		}
		else if(negative > 0) {
Example #11
0
	static void eval(Thread& thread, A const& a, Integer const& d, int64_t nonzero, Value& out)
	{
		std::set<Integer::Element> index; 
		typename A::Element const* ae = a.v();
		typename Integer::Element const* de = d.v();
		int64_t length = d.length();
		for(int64_t i = 0; i < length; i++) if(-de[i] > 0 && -de[i] <= (int64_t)a.length()) index.insert(-de[i]);
		// iterate through excluded elements copying intervening ranges.
		A r(a.length()-index.size());
		typename A::Element* re = r.v();
		int64_t start = 1;
		int64_t k = 0;
		for(std::set<Integer::Element>::const_iterator i = index.begin(); i != index.end(); ++i) {
			int64_t end = *i;
			for(int64_t j = start; j < end; j++) re[k++] = ae[j-1];
			start = end+1;
		}
		for(int64_t j = start; j <= a.length(); j++) re[k++] = ae[j-1];
		out = r;
	}
Example #12
0
Integer Integer::operator+(Integer value) const
{
    ubyte*  addend;
    ubyte*  offset;
    short   result;
    Integer sum = *this;


    if (sum.size == value.size) {
        if ((*sum.msb & SIGN_BIT) == (*value.msb & SIGN_BIT) && (sbyte)(abs(*sum.msb) + abs(*value.msb) + 1) < 0) {
            sum.resize(sum.size + 1);
        }
    } else if (sum.size < value.size) {
        if ((sbyte)abs(*this->msb) + 1 > 0) {
            sum.resize(value.size);
        } else {
            sum.resize(value.size + 1);
        }        
    } else {
        if ((sbyte)abs(*sum.msb) + 1 < 0) {
            sum.resize(sum.size + 1);
        }
    }
    value.resize(sum.size);
    

    result = 0;
    offset = sum.value;
    addend = value.value;
    while (addend <= (ubyte*)value.msb) {
        result = *offset + *addend;
        *offset = (ubyte)result;
        
        result = result >> (sizeof(ubyte) * CHAR_BIT);
        ++offset;
        ++addend;
    }
    while (result != 0 && offset <= (ubyte*)sum.msb) {
        result = *offset + result;
        *offset = (ubyte)result;

        result = result >> (sizeof(ubyte) * CHAR_BIT);
        ++offset;
    }

    if (
        (*sum.msb == 0 && sum.size > 1 && (*(sum.msb - 1) & SIGN_BIT) == 0)
        ||
        (*sum.msb == -1 && sum.size > 1 && *(sum.msb - 1) < 0)
    ) {
        //If the most significant byte of the integer is 0, or the most significant byte is filled with ones and the preceding byte's sign bit is set, decrease the size of the block of memory maintained by the sum integer by one.
        sum.resize(sum.size - 1);
    }

    return sum;
}
Example #13
0
// Returns (*this)^2.
Integer Integer::square()
{
    if (size() < MIN_KARATSUBA_SQUARE) {
        return multiply(*this, *this);
    }

    unsigned int i, half = (size() + 1) / 2;
    Integer a0, a1;
    split(*this, a0, a1, half);
    Integer square0 = a0.square();
    Integer square1 = a1.square();
    Integer ans;
    ans.set_size(size() + size());

    for (i = 0; i < 2 * half; i++) {
        ans[i] = square0[i];
    }

    for (i = 2 * half; i < ans.size(); i++) {
        ans[i] = square1[i - 2 * half];
    }

    Integer square2 = (a0 + a1).square();
    square2 -= square0;
    square2 -= square1;
    int n, carry = 0;

    for (i = half; i < ans.size(); i++) {
        n = ans[i] + square2[i - half] + carry;
        carry = n / BASE;
        ans[i] = n % BASE;
    }

    if (carry > 0) {
        ans[i++] = carry;
    }

    ans.adjust();

    return ans;
}
vector<bool> Receiver::decode(Integer v) {
    vector<bool> res(com.l);
    for(unsigned i = 0; i < com.l; ++i) {
        res[i] = com.S[i] ^ v.GetBit(0);
        v = a_times_b_mod_c(v, v, com.n);
    }

    if (v != com.u) {
        throw SanityException("v != com.u");
    }
    return res;
}
Example #15
0
Integer HashPointMessage(const ECP& ec, const ECPPoint& R,
	const byte* message, int mlen, bool compress = false)
{
	const int digestsize = 256/8;
	SHA3 sha(digestsize);

	int len = ec.EncodedPointSize();
	byte *buffer = new byte[len];
	ec.EncodePoint(buffer, R, compress);
	sha.Update(buffer, len);
	delete[] buffer;

	sha.Update(message, mlen);

	byte digest[digestsize];
	sha.Final(digest);
	
	Integer ans;
	ans.Decode(digest, digestsize);
	return ans;
}
Example #16
0
Integer Integer::add_if_different_sign(const Integer &arg) const {
	if (abs(*this) == abs(arg))
		return 0;

	Integer res;

	// atgaa -> abs (of) this (is) greater (than) abs (of) arg: 1 or -1
	int atgaa = (abs(*this) > abs(arg)) * 2 - 1;

	do res.push_back(0);
	while (res.size() < std::max(size(), arg.size()));

	for (size_t i = 0; i < res.size(); ++i) {
		if (i < size())
			res[i] += (*this)[i] * atgaa;

		if (i < arg.size())
			res[i] += arg[i] * -atgaa;

		if (res[i] < 0) {
			res[i] += 10;
			res[i + 1]--;
		}
	}

	res.sign = (atgaa == 1 ? sign : arg.sign);

	while (!res[-1])
		res.vec->pop_back();

	return res;
}
void EGLViewProtocol::handleTouchesMove(int num, int ids[], float xs[], float ys[])
{
    Set set;
    for (int i = 0; i < num; ++i)
    {
        int id = ids[i];
        float x = xs[i];
        float y = ys[i];

        Integer* pIndex = (Integer*)s_TouchesIntergerDict.objectForKey(id);
        if (pIndex == NULL) {
            CCLOG("if the index doesn't exist, it is an error");
            continue;
        }

        CCLOGINFO("Moving touches with id: %d, x=%f, y=%f", id, x, y);
        Touch* pTouch = s_pTouches[pIndex->getValue()];
        if (pTouch)
        {
			pTouch->setTouchInfo(pIndex->getValue(), (x - _viewPortRect.origin.x) / _scaleX, 
								(y - _viewPortRect.origin.y) / _scaleY);
            
            set.addObject(pTouch);
        }
        else
        {
            // It is error, should return.
            CCLOG("Moving touches with id: %d error", id);
            return;
        }
    }

    if (set.count() == 0)
    {
        CCLOG("touchesMoved: count = 0");
        return;
    }

    _delegate->touchesMoved(&set, NULL);
}
bool WestwoodRSA::Encrypt(unsigned char *in_buffer, unsigned int length, unsigned char *out_buffer)
{
    bool success = false;
    if (length > 0)
    {
        Integer e(WWRSA_e);
        Integer N(WWRSA_N);
        Integer M;
        Integer C;
        unsigned int offset = 0;
        unsigned int remaining = length;
        while (remaining >= WWRSA_BLOCK_SIZE)
        {
            M.Decode(in_buffer + offset, WWRSA_BLOCK_SIZE);
            C = a_exp_b_mod_c(M, e, N);
            C.Encode(out_buffer + offset, WWRSA_BLOCK_SIZE);
            offset += WWRSA_BLOCK_SIZE;
            remaining -= WWRSA_BLOCK_SIZE;
        }
        if (remaining > 0)
        {
            unsigned char buffer[WWRSA_BLOCK_SIZE];
            memcpy(buffer, in_buffer + offset, remaining);
            memset(buffer + remaining, 0, WWRSA_BLOCK_SIZE - remaining);
            M.Decode(buffer, WWRSA_BLOCK_SIZE);
            C = a_exp_b_mod_c(M, e, N);
            C.Encode(out_buffer + offset, WWRSA_BLOCK_SIZE);
        }
        success = true;
    }

    return success;
};
Example #19
0
Signature Secp256k1PP::sign(Secret const& _key, h256 const& _hash)
{
	// assumption made by signing alogrithm
	assert(m_q == m_qs);
	
	Signature sig;
	
	Integer k(kdf(_key, _hash).data(), 32);
	if (k == 0)
		BOOST_THROW_EXCEPTION(InvalidState());
	k = 1 + (k % (m_qs - 1));
	
	ECP::Point rp;
	Integer r;
	{
		Guard l(x_params);
		rp = m_params.ExponentiateBase(k);
		r = m_params.ConvertElementToInteger(rp);
	}
	sig[64] = 0;
//	sig[64] = (r >= m_q) ? 2 : 0;
	
	Integer kInv = k.InverseMod(m_q);
	Integer z(_hash.asBytes().data(), 32);
	Integer s = (kInv * (Integer(_key.data(), 32) * r + z)) % m_q;
	if (r == 0 || s == 0)
		BOOST_THROW_EXCEPTION(InvalidState());
	
//	if (s > m_qs)
//	{
//		s = m_q - s;
//		if (sig[64])
//			sig[64] ^= 1;
//	}
	
	sig[64] |= rp.y.IsOdd() ? 1 : 0;
	r.Encode(sig.data(), 32);
	s.Encode(sig.data() + 32, 32);
	return sig;
}
Example #20
0
std::string Root::toString() {
	if (typeid(*this->root) == typeid(Integer)) {
		Integer * intRoot = dynamic_cast<Integer*>(this->root);
		if (intRoot->getInt() == 2) {
			return "sqrt:(" + this->base->toString() + ")";
		}
		else if (intRoot->getInt() < 0 && typeid(*this->base) == typeid(Placeholder)) {
			return "(" + this->root->toString() + ")rt:" + this->base->toString();
		}
		else if (intRoot->getInt() < 0 && typeid(*this->base) != typeid(Placeholder)) {
			return "(" + this->root->toString() + ")rt:(" + this->base->toString() + ")";
		}
	}
	else if (typeid(*this->root) == typeid(Placeholder) && typeid(*this->base) == typeid(Placeholder)) {
		return "(" + this->root->toString() + ")rt:" + this->base->toString();
	}
	else if (typeid(*this->root) == typeid(Placeholder) && typeid(*this->base) != typeid(Placeholder)) {
		return "(" + this->root->toString() + ")rt:(" + this->base->toString() + ")";
	}

	return this->root->toString() + "rt:(" + this->base->toString() + ")";
}
Example #21
0
int factor_pollard_pm1_method(const Ptr<RCP<const Integer>> &f,
                              const Integer &n, unsigned B, unsigned retries)
{
    int ret_val = 0;
    integer_class rop, nm4, c;
    gmp_randstate_t state;

    gmp_randinit_default(state);
    gmp_randseed_ui(state, retries);
    nm4 = n.as_integer_class() - 4;

    for (unsigned i = 0; i < retries and ret_val == 0; ++i) {
        mp_urandomm(c, state, nm4);
        c = c + 2;
        ret_val = _factor_pollard_pm1_method(rop, n.as_integer_class(), c, B);
    }

    if (ret_val != 0)
        *f = integer(std::move(rop));
    gmp_randclear(state);
    return ret_val;
}
Example #22
0
void PrimeSieve::SieveSingle(std::vector<bool> &sieve, word16 p, const Integer &first, const Integer &step, word16 stepInv)
{
	if (stepInv)
	{
		size_t sieveSize = sieve.size();
		size_t j = (word32(p-(first%p))*stepInv) % p;
		// if the first multiple of p is p, skip it
		if (first.WordCount() <= 1 && first + step*long(j) == p)
			j += p;
		for (; j < sieveSize; j += p)
			sieve[j] = true;
	}
}
Example #23
0
Integer MihailescuProvablePrime(RandomNumberGenerator &rng, unsigned int pbits)
{
	Integer p;
	Integer minP = Integer::Power2(pbits-1);
	Integer maxP = Integer::Power2(pbits) - 1;

	if (maxP <= Integer(s_lastSmallPrime).Squared())
	{
		// Randomize() will generate a prime provable by trial division
		p.Randomize(rng, minP, maxP, Integer::PRIME);
		return p;
	}

	unsigned int qbits = (pbits+2)/3 + 1 + rng.GenerateWord32(0, pbits/36);
	Integer q = MihailescuProvablePrime(rng, qbits);
	Integer q2 = q<<1;

	while (true)
	{
		// this initializes the sieve to search in the arithmetic
		// progression p = p_0 + \lambda * q2 = p_0 + 2 * \lambda * q,
		// with q the recursively generated prime above. We will be able
		// to use Lucas tets for proving primality. A trick of Quisquater
		// allows taking q > cubic_root(p) rather then square_root: this
		// decreases the recursion.

		p.Randomize(rng, minP, maxP, Integer::ANY, 1, q2);
		PrimeSieve sieve(p, STDMIN(p+PrimeSearchInterval(maxP)*q2, maxP), q2);

		while (sieve.NextCandidate(p))
		{
			if (FastProbablePrimeTest(p) && ProvePrime(p, q))
				return p;
		}
	}

	// not reached
	return p;
}
Example #24
0
  size_t
hash(const Opnd opnd)
{
  if (is_reg(opnd)) {
    int reg = get_reg(opnd);
    if (is_virtual_reg(opnd))
      reg = -(reg + 1);
    return reg << 1;
  } else if (is_var(opnd)) {
    return (size_t)get_var(opnd) | 1;
  } else if (is_immed_integer(opnd)) {
    Integer i = get_immed_integer(opnd);
    if (i.is_c_string_int())
      return string_hash(i.chars());
    else
      return i.c_long();
  } else if (is_immed_string(opnd)) {
    return string_hash(get_immed_string(opnd).chars());
  }
  claim(false, "Operand kind %d isn't yet hashable", get_kind(opnd));
  return 0;
}
Example #25
0
RCP<const Number> Complex::powcomp(const Integer &other) const {
    if (this->is_re_zero()) {
        // Imaginary Number raised to an integer power.
        RCP<const Number> im = Rational::from_mpq(this->imaginary_);
        long rem = mod(other, *integer(4))->as_int();
        RCP<const Number> res;
        if (rem == 0) {
            res = one;
        } else if (rem == 1) {
            res = I;
        } else if (rem == 2) {
            res = minus_one;
        } else {
            res = mulnum(I, minus_one);
        }
        return mulnum(im->pow(other), res);
    } else if (other.is_positive()) {
        return pow_number(*this, other.as_int());
    } else {
        return one->div(*pow_number(*this, -1 * other.as_int()));
    }
};
Example #26
0
int main()
{
  Integer i = new Integer(), j = new Integer(3);
  Integer k = j;
  if(i.value() != 0 || j.value() != 3 || k.value() != 3)
  {
    cout << "Test 1 failed- basics" << endl;
    return 1;
  }
  i = 5;
  if(i.value() != 5)
  {
    cout << "Test 2 failed- assignment" << endl;
    return 1;
  }
  int a = i;
  if(a != 5)
  {
    cout << "Test 3 failed- integer assignment" << endl;
    return 1;
  }
}
Example #27
0
void PrimeSieve::SieveSingle(std::vector<bool> &sieve, word p, const Integer &first, const Integer &step, word stepInv)
{
	if (stepInv)
	{
		unsigned int sieveSize = sieve.size();
		word j = word((dword(p-(first%p))*stepInv) % p);
		// if the first multiple of p is p, skip it
		if (first.WordCount() <= 1 && first + step*j == p)
			j += p;
		for (; j < sieveSize; j += p)
			sieve[j] = true;
	}
}
Example #28
0
RCP<const Integer> iabs(const Integer &n)
{
    mpz_class m;
    mpz_t m_t;

    mpz_init(m_t);
    mpz_abs(m_t, n.as_mpz().get_mpz_t());
    m = mpz_class(m_t);

    mpz_clear(m_t);

    return integer(mpz_class(m));
}
Example #29
0
int factor_pollard_pm1_method(const Ptr<RCP<const Integer>> &f, const Integer &n,
                              unsigned B, unsigned retries)
{
    int ret_val = 0;
    mpz_class rop, nm4, c;
    gmp_randstate_t state;

    gmp_randinit_default(state);
    gmp_randseed_ui(state, retries);
    nm4 = n.as_mpz() - 4;

    for (unsigned i = 0; i < retries && ret_val == 0; i++) {
        mpz_urandomm(c.get_mpz_t(), state, nm4.get_mpz_t());
        c = c + 2;
        ret_val = _factor_pollard_pm1_method(rop, n.as_mpz(), c, B);
    }

    if (ret_val != 0)
        *f = integer(rop);

    return ret_val;
}
Example #30
0
int i_nth_root(const Ptr<RCP<const Integer>> &r, const Integer &a,
               unsigned long int n)
{
    if (n == 0)
        throw SymEngineException("i_nth_root: Can not find Zeroth root");

    int ret_val;
    integer_class t;

    ret_val = mp_root(t, a.as_integer_class(), n);
    *r = integer(std::move(t));

    return ret_val;
}