Large mathematical operation c++ - c++

I want large mathematical operation in c++.
long long h= 4294967295;
long long d=7910266469;
long long n=10021211227;
long long result;
I am need calculate this is:
h^d mod n
result=pow(h,d) % n;
I dont know which type using.Please help me for choose type numbers..
Thanks

Look at this wikipedia article.
There is a pretty nice example with the following memory-efficient pseudo code:
function modular_pow(base, exponent, modulus)
if modulus = 1 then return 0
c := 1
for e_prime = 1 to exponent
c := (c * base) mod modulus
return c
There is even a example for beeing memory-efficient and using less operations. I think getting the c++ code out of it should be possible.
If you use this method, long long for your solution should be fine.
Not tested but a simple 1:1 translation from the pseudo code from above...
long long result = 1;
int i;
for( i=0; i<d;i++){
result = (result * h) % n;
}

Related

Understanding this way of computing ( x^e mod n)

working on a RSA encryption in c++ and found that the pow() function in cmath was giving me the incorrect result.
after looking online I came across some code that would do the above process for me but I am having difficulty understanding it.
this is the code:
long long int modpow(long long int base, long long int exp, long long int modulus) {
base %= modulus;
long long int result = 1;
while (exp > 0) {
if (exp & 1) {
result = (result * base) % modulus;
}
base = (base * base) % modulus;
exp >>= 1;
}
return result;
}
(this code isn't the original)
I am struggling with understanding this function.
I know that exp >>=1; is a left shift 1 bit and (exp & 1) returns 1 or 0 based on the least significant bit but what i dont understand is how that contributes to the final answer.
for example:
if (exp & 1) {
result = (result * base) % modulus;
}
what is the purpose of (result * base) % modulus if exp is odd?
hoping someone can please explain this function to me as I dont want to just copy it over.
The code was written to be "clever" instead of clear. This cryptic style usually should not be done outside core libraries (where performance is crucial), and even when it is used, it would be nice to have comments explaining what is going on.
Here is an annotated version of the code.
long long int modpow(long long int base, long long int exp, long long int modulus)
{
base %= modulus; // Eliminate factors; keeps intermediate results smaller
long long int result = 1; // Start with the multiplicative unit (a.k.a. one)
// Throughout, we are calculating:
// `(result*base^exp)%modulus`
while (exp > 0) { // While the exponent has not been exhausted.
if (exp & 1) { // If the exponent is odd
result = (result * base) % modulus; // Consume one application of the base, logically
// (but not actually) reducing the exponent by one.
// That is: result * base^exp == (result*base)*base^(exp-1)
}
base = (base * base) % modulus; // The exponent is logically even. Apply B^(2n) == (B^2)^n.
exp >>= 1; // The base is squared and the exponent is divided by 2
}
return result;
}
Does that make more sense now?
For those wondering how this cryptic code could be made clearer, I present the following version. There are three main improvements.
First, bitwise operations have been replaced by the equivalent arithmetic operations. If one were to prove that the algorithm works, one would use arithmetic, not bitwise operators. In fact, the algorithm works regardless of how the numbers are represented – there need not be a concept of "bits", much less of "bitwise operators". Thus the natural way to implement this algorithm is with arithmetic. Using bitwise operators removes clarity with almost no benefit. Compilers are smart enough to produce identical machine code, with one exception. Since exp was declared long long int instead of long long unsigned, there is an extra step when calculating exp /= 2 compared to exp >>= 1. (I do not know why exp is signed; the function is both conceptually meaningless and technically incorrect for negative exponents.) See also premature-optimization.
Second, I created a helper function for improved readability. While the improvement is minor, it comes at no performance cost. I'd expect the function to be inlined by any compiler worth its salt.
// Wrapper for detecting if an integer is odd.
bool is_odd(long long int n)
{
return n % 2 != 0;
}
Third, comments have been added to explain what is going on. While some people (not I) might think that "the standard right-to-left modular binary exponentiation algorithm" is required knowledge for every C++ coder, I prefer to make fewer assumptions about the people who might read my code in the future. Especially if that person is me, coming back to the code after years away from it.
And now, the code, as I would prefer to see the current functionality written:
// Returns `(base**exp) % modulus`, where `**` denotes exponentiation.
// Assumes `exp` is non-negative.
// Assumes `modulus` is non-zero.
// If `exp` is zero, assumes `modulus` is neither 1 nor -1.
long long int modpow(long long int base, long long int exp, long long int modulus)
{
// NOTE: This algorithm is known as the "right-to-left binary method" of
// "modular exponentiation".
// Throughout, we'll keep numbers smallish by using `(A*B) % C == ((A%C)*B) % C`.
// The first application of this principle is to the base.
base %= modulus;
// Intermediate results will be stored modulo `modulus`.
long long int result = 1;
// Loop invariant:
// The value to return is `(result * base**exp) % modulus`.
// Loop goal:
// Reduce `exp` to the point where `base**exp` is 1.
while (exp > 0) {
if ( is_odd(exp) ) {
// Shift one factor of `base` to `result`:
// `result * base^exp == (result*base) * base^(exp-1)`
result = (result * base) % modulus;
//--exp; // logically happens, but optimized out.
// We are now in the "`exp` is even" case.
}
// Reduce the exponent by increasing the base: `B**(2n) == (B**2)**n`.
base = (base * base) % modulus;
exp /= 2;
}
return result;
}
The resulting machine code is almost identical. If performance really is critical, I could see going back to exp >>= 1, but only if changing the type of exp is not allowed.

How do i calculate combinations of n taken by k for large numbers in modulo 100003?

The maximum value of n is 100 000 and k can be anywhere from 0 to 100 000. The problem asks to calculate the value modulo 100 003. So I've used a function to calculate the factorial of n,n-k and k and then print fact(n)/(fact(n-k)*fact(k))% 100 003. What am I doing wrong and what would be the solution?
long long int fact (int z)
{
long long int r;
if(z<=1)return 1;
r=1LL*z*fact(z-1);
return r;
}
A long long is not big enough to hold fact(n) for interesting n, so you need a smarter algorithm.
applying the mod 100003 as you multiply is an easy way to keep things in range. But modular division is messy and in this case unnecessary.
Think about how to compute fact(n)/( fact(n-k)*fact(k) ) without ever needing to divide any big or modular numbers.
It will overflow for most z (z = 105 already overflows, for example).
Fortunately the integers modulo 100003 form a field (because 100003 is prime), so the entire calculation (even though it includes a division) can be done modulo 100003, thus preventing any overflow.
Most operations will be the same (except the extra modulo operation), but division becomes multiplication by the modular multiplicative inverse, which you can find using the extended Euclidian algorithm.
ncr=n!/((n-r)!*r!)
(a/b)%p!=((a%p)/(b%p))%p
using fermat little theorem we can compute this
Here fact() means factorial.
nCr % p = (fac[n] modInverse(fac[r]) % p modInverse(fac[n-r]) % p) % p;
Here modInverse() means modular inverse under
modulo p.
calculating ,moduloINverse if p is prime as give
long long modInverse( long long n, int p)
{
return expo(n, p - 2, p);
}
long long expo(long long a, long long b, long long mod) {
long long res = 1;
while (b > 0) {
if (b & 1)res = (res * a) % mod;
a = (a * a) % mod;
b = b >> 1;}
return res;}

How to Calculate 2^x mod n = 1 in less than 1 second

I want to write the program that Calculate 2^x mod n = 1 we have n is an integer but, we should calculate x.I wrote the code but my code work too slow in big n.Can you suggest me a good way that work less than 1 second to solve this problem.
here is my code:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
long long int n,cntr=1,cheak;
cin >> n;
while (1)
{
if (n % 2 == 0)
{
break;
}
cheak=pow(2, cntr);
if (cheak % n == 1)
break;
cntr++;
}
cout << cntr << endl;
}
Some suggested modifications to your current approach: Note: a better approach follows!
Change your long long int to unsigned long long int. This will give you one more bit.
Change while (1) to while (cntr < 64). The size of unsigned long long is likely only 64 bits. (It's guaranteed to be at least 64 bits, but not larger than that.) You would then need to check whether your loop succeeded, however.
Change cheak to calculate 2n as 1ull << cntr. Make sure to include the ull suffix, which says this is an unsigned long long.
The << operator shifts bits to the left. Shifting all the bits to the left by 1 doubles the integer value of the number, assuming no bits "shifted away" off the left of the value. So, 1 << n will compute 2n.
The suffix ull indicates an integer constant is an unsigned long long. If you omit this suffix, 1 will be treated as an integer, and shift values above 31 will not do what you want.
However, all of the above are merely refinements on your current approach. It's worth understanding those refinements to better understand the language. They don't, however, look at the bigger picture.
Modular multiplication allows you to find (A * B) mod C as ( (A mod C) * (B mod C) ) mod C. How does that help us here?
We can rewrite the entire algorithm in a way that only limits N and X to the precision of the machine integers, and not 2N:
int main()
{
unsigned int modulus;
unsigned int raised = 2;
int power = 1;
std::cin >> modulus;
if (modulus % 2 == 1)
{
while (raised % modulus != 1)
{
raised = ((unsigned long long)raised * 2) % modulus;
power++;
}
std::cout << power << std::endl;
} else
{
std::cout << "modulus must be odd" << std::endl;
}
}
The cast to unsigned long long above allows modulus to be as large as 232 - 1, assuming unsigned int is 32 bits, without the computation overflowing.
With this approach, I was able to very quickly find answers even for very large inputs. For example, 111111111 returns 667332. I verified 2677332 mod 111111111 == 1 using the arbitrary precision calculator bc.
It's very fast. It computed 22323860 mod 4294967293 == 1 in less than 0.07 seconds on my computer.
Epilog: This highlights an important principle in programming: Really, this was a math problem more than a programming problem. Finding an efficient solution required knowing more about the problem domain than it did knowing about C++. The actual C++ code was trivial once we identified the correct mathematical approach.
It often goes this way, whether it's the mathematics or some other algorithmic aspect. And, it shouldn't surprise you to learn that discrete mathematics is where many of our graph and set algorithms come from. The programming language itself is a small piece of the big picture.
For each k between 1 and ceil(sqrt(n)), compute 2^k mod n and 2^(k ceil(sqrt(n))) mod n. Then compute the modular inverse of each 2^k. Sort all of the inverse(2^k)s into an array foo and the 2^(k ceil(sqrt(n))s into an array bar. There will be at least one value in common between the two arrays; find it. Say inverse(2^a) = 2^(b ceil(sqrt(n))). Then 2^(a + b ceil(sqrt(n))) = 1 (mod n).
How's your professor's sense of humor?
#include <iostream>
int main() { std::cout << 0 << '\n'; }
always prints a correct answer to the problem as stated.
pow is quite expensive in calculations, but if you have 2 as its first argument, you can better do a shift left, as shift left is equal to multiplying by 2:
cheak = (1 << cntr);

Calculating pow(a,b) mod n

I want to calculate ab mod n for use in RSA decryption. My code (below) returns incorrect answers. What is wrong with it?
unsigned long int decrypt2(int a,int b,int n)
{
unsigned long int res = 1;
for (int i = 0; i < (b / 2); i++)
{
res *= ((a * a) % n);
res %= n;
}
if (b % n == 1)
res *=a;
res %=n;
return res;
}
You can try this C++ code. I've used it with 32 and 64-bit integers. I'm sure I got this from SO.
template <typename T>
T modpow(T base, T exp, T modulus) {
base %= modulus;
T result = 1;
while (exp > 0) {
if (exp & 1) result = (result * base) % modulus;
base = (base * base) % modulus;
exp >>= 1;
}
return result;
}
You can find this algorithm and related discussion in the literature on p. 244 of
Schneier, Bruce (1996). Applied Cryptography: Protocols, Algorithms, and Source Code in C, Second Edition (2nd ed.). Wiley. ISBN 978-0-471-11709-4.
Note that the multiplications result * base and base * base are subject to overflow in this simplified version. If the modulus is more than half the width of T (i.e. more than the square root of the maximum T value), then one should use a suitable modular multiplication algorithm instead - see the answers to Ways to do modulo multiplication with primitive types.
In order to calculate pow(a,b) % n to be used for RSA decryption, the best algorithm I came across is Primality Testing 1) which is as follows:
int modulo(int a, int b, int n){
long long x=1, y=a;
while (b > 0) {
if (b%2 == 1) {
x = (x*y) % n; // multiplying with base
}
y = (y*y) % n; // squaring the base
b /= 2;
}
return x % n;
}
See below reference for more details.
1) Primality Testing : Non-deterministic Algorithms – topcoder
Usually it's something like this:
while (b)
{
if (b % 2) { res = (res * a) % n; }
a = (a * a) % n;
b /= 2;
}
return res;
The only actual logic error that I see is this line:
if (b % n == 1)
which should be this:
if (b % 2 == 1)
But your overall design is problematic: your function performs O(b) multiplications and modulus operations, but your use of b / 2 and a * a implies that you were aiming to perform O(log b) operations (which is usually how modular exponentiation is done).
Doing the raw power operation is very costly, hence you can apply the following logic to simplify the decryption.
From here,
Now say we want to encrypt the message m = 7, c = m^e mod n = 7^3 mod 33
= 343 mod 33 = 13. Hence the ciphertext c = 13.
To check decryption we compute m' = c^d mod n = 13^7 mod 33 = 7. Note
that we don't have to calculate the full value of 13 to the power 7
here. We can make use of the fact that a = bc mod n = (b mod n).(c mod
n) mod n so we can break down a potentially large number into its
components and combine the results of easier, smaller calculations to
calculate the final value.
One way of calculating m' is as follows:- Note that any number can be
expressed as a sum of powers of 2. So first compute values of 13^2,
13^4, 13^8, ... by repeatedly squaring successive values modulo 33. 13^2
= 169 ≡ 4, 13^4 = 4.4 = 16, 13^8 = 16.16 = 256 ≡ 25. Then, since 7 = 4 + 2 + 1, we have m' = 13^7 = 13^(4+2+1) = 13^4.13^2.13^1 ≡ 16 x 4 x 13 = 832
≡ 7 mod 33
Are you trying to calculate (a^b)%n, or a^(b%n) ?
If you want the first one, then your code only works when b is an even number, because of that b/2. The "if b%n==1" is incorrect because you don't care about b%n here, but rather about b%2.
If you want the second one, then the loop is wrong because you're looping b/2 times instead of (b%n)/2 times.
Either way, your function is unnecessarily complex. Why do you loop until b/2 and try to multiply in 2 a's each time? Why not just loop until b and mulitply in one a each time. That would eliminate a lot of unnecessary complexity and thus eliminate potential errors. Are you thinking that you'll make the program faster by cutting the number of times through the loop in half? Frankly, that's a bad programming practice: micro-optimization. It doesn't really help much: You still multiply by a the same number of times, all you do is cut down on the number of times testing the loop. If b is typically small (like one or two digits), it's not worth the trouble. If b is large -- if it can be in the millions -- then this is insufficient, you need a much more radical optimization.
Also, why do the %n each time through the loop? Why not just do it once at the end?
Calculating pow(a,b) mod n
A key problem with OP's code is a * a. This is int overflow (undefined behavior) when a is large enough. The type of res is irrelevant in the multiplication of a * a.
The solution is to ensure either:
the multiplication is done with 2x wide math or
with modulus n, n*n <= type_MAX + 1
There is no reason to return a wider type than the type of the modulus as the result is always represent by that type.
// unsigned long int decrypt2(int a,int b,int n)
int decrypt2(int a,int b,int n)
Using unsigned math is certainly more suitable for OP's RSA goals.
Also see Modular exponentiation without range restriction
// (a^b)%n
// n != 0
// Test if unsigned long long at least 2x values bits as unsigned
#if ULLONG_MAX/UINT_MAX - 1 > UINT_MAX
unsigned decrypt2(unsigned a, unsigned b, unsigned n) {
unsigned long long result = 1u % n; // Insure result < n, even when n==1
while (b > 0) {
if (b & 1) result = (result * a) % n;
a = (1ULL * a * a) %n;
b >>= 1;
}
return (unsigned) result;
}
#else
unsigned decrypt2(unsigned a, unsigned b, unsigned n) {
// Detect if UINT_MAX + 1 < n*n
if (UINT_MAX/n < n-1) {
return TBD_code_with_wider_math(a,b,n);
}
a %= n;
unsigned result = 1u % n;
while (b > 0) {
if (b & 1) result = (result * a) % n;
a = (a * a) % n;
b >>= 1;
}
return result;
}
#endif
int's are generally not enough for RSA (unless you are dealing with small simplified examples)
you need a data type that can store integers up to 2256 (for 256-bit RSA keys) or 2512 for 512-bit keys, etc
Here is another way. Remember that when we find modulo multiplicative inverse of a under mod m.
Then
a and m must be coprime with each other.
We can use gcd extended for calculating modulo multiplicative inverse.
For computing ab mod m when a and b can have more than 105 digits then its tricky to compute the result.
Below code will do the computing part :
#include <iostream>
#include <string>
using namespace std;
/*
* May this code live long.
*/
long pow(string,string,long long);
long pow(long long ,long long ,long long);
int main() {
string _num,_pow;
long long _mod;
cin>>_num>>_pow>>_mod;
//cout<<_num<<" "<<_pow<<" "<<_mod<<endl;
cout<<pow(_num,_pow,_mod)<<endl;
return 0;
}
long pow(string n,string p,long long mod){
long long num=0,_pow=0;
for(char c: n){
num=(num*10+c-48)%mod;
}
for(char c: p){
_pow=(_pow*10+c-48)%(mod-1);
}
return pow(num,_pow,mod);
}
long pow(long long a,long long p,long long mod){
long res=1;
if(a==0)return 0;
while(p>0){
if((p&1)==0){
p/=2;
a=(a*a)%mod;
}
else{
p--;
res=(res*a)%mod;
}
}
return res;
}
This code works because ab mod m can be written as (a mod m)b mod m-1 mod m.
Hope it helped { :)
use fast exponentiation maybe..... gives same o(log n) as that template above
int power(int base, int exp,int mod)
{
if(exp == 0)
return 1;
int p=power(base, exp/2,mod);
p=(p*p)% mod;
return (exp%2 == 0)?p:(base * p)%mod;
}
This(encryption) is more of an algorithm design problem than a programming one. The important missing part is familiarity with modern algebra. I suggest that you look for a huge optimizatin in group theory and number theory.
If n is a prime number, pow(a,n-1)%n==1 (assuming infinite digit integers).So, basically you need to calculate pow(a,b%(n-1))%n; According to group theory, you can find e such that every other number is equivalent to a power of e modulo n. Therefore the range [1..n-1] can be represented as a permutation on powers of e. Given the algorithm to find e for n and logarithm of a base e, calculations can be significantly simplified. Cryptography needs a tone of math background; I'd rather be off that ground without enough background.
For my code a^k mod n in php:
function pmod(a, k, n)
{
if (n==1) return 0;
power = 1;
for(i=1; i<=k; $i++)
{
power = (power*a) % n;
}
return power;
}
#include <cmath>
...
static_cast<int>(std::pow(a,b))%n
but my best bet is you are overflowing int (IE: the number is two large for the int) on the power I had the same problem creating the exact same function.
I'm using this function:
int CalculateMod(int base, int exp ,int mod){
int result;
result = (int) pow(base,exp);
result = result % mod;
return result;
}
I parse the variable result because pow give you back a double, and for using mod you need two variables of type int, anyway, in a RSA decryption, you should just use integer numbers.

modulus operations on long long in c++

I am working on prime factorization on large numbers (mainly, project 3 # project Euler. I need to use the modulus on numbers declared as long long. Everytime I try to modulus that gigantic number I get a floating point exception. Any help would be profusely appreciated. Thanks.
I have run this through gdb and see what's happening. Below is my code. It's very rough logic at this point. Please do not give me the answer to the problem. I will gladly accept help on making this better, just please do not give me the straight up answer. Thanks :)
long factor(long number) {
string br = "\n\r";
long x = 0;
/*this modulus variable is an attempt
to move the answer into a long long container
to see if that solves my floating point exception,
it didn't*/
long long modulus;
while(x <= number) {
modulus = number % x;
if(modulus == 0) {
cout << number/x << br;
return factor(number/x);
}//if number % x
else {
return x;
}//else
x++;
}//while
}//factor
Don't try to mod by 0, it's undefined! Doing so will result in a divide-by-zero error.
long x = 0;
modulus = number % x; // x is 0 here and thus not valid
To expand a bit on my answer, per Wikipedia's article on Modulo Operations
a modulo 0 is undefined in the majority of systems, although some do define it to be a.
Start with
long x = 1 ;
to avoid a division by zero.