Finding multiplicative inverse of x in Z(n), extended Euclides algorithm - c

I'm trying to find multiplicative inverse of x using GMP library; I know there is a built-in function, but I want to write my own.
This is my extended Euclides algorithm implementation:
void extended_euclides(mpz_t r,mpz_t x,mpz_t y,mpz_t a, mpz_t b){
mpz_t r_2,r_1,x_2,x_1,y_2,y_1,q,tmp;
mpz_inits(r,x,y,NULL);
mpz_init_set(r_2,a);
mpz_init_set(r_1,b);
mpz_init_set_ui(x_2,1);
mpz_init_set_ui(y_2,0);
mpz_init_set_ui(x_1,0);
mpz_init_set_ui(y_1,1);
mpz_init_set_ui(q,0);
mpz_init_set_ui(tmp,0);
do{
mpz_fdiv_qr(q,r,r_2,r_1);
//x
mpz_mul(tmp,q,x_1);
mpz_sub(x,x_2,tmp);
//y
mpz_mul(tmp,q,y_1);
mpz_sub(y,y_2,tmp);
mpz_set(x_2,x_1);
mpz_set(x_1,x);
mpz_set(y_2,y_1);
mpz_set(y_1,y);
mpz_set(r_2,r_1);
mpz_set(r_1,r);
}while(mpz_cmp_ui(r,0)!=0);
mpz_set(r,r_1);
mpz_set(x,x_2);
mpz_set(y,y_2);
mpz_clears(r_2,r_1,x_2,y_2,x_1,y_1,q,tmp,NULL);
}
It works fine for all small numbers and for some big numbers but not for all, and I don't known why. Example numbers for which it doesn't work:
a=99493485436357509294299436068793093643611893389896126764674829386592836165461754466092785338067969036756243799506670417432259164622123562781847156006846186608672621538507317131150760491084706497192710261706218845591564505899259562270249156644155861984060987885202877640033289062925176647874893491223532714128
b=202287573793610924311033969010234326099
if I change b to:
b=202287573793610924311033969010234326199
it works fine (I changed first 0 from right side to 1); the result I get is:
-26280231501456618600907242915048902345641123248519760433640466576442417888637174268721528225514196371138187569270563190841794774411834326405888357503240710494456394764379952360665884114850067939183395690214208147924280567331029828334399167395301049535292042342359035346464834873473183771024039179653285711685
The correct result, calculated by GMP function and checked by me in equation b*b^-1 ≡ 1 mod (a), is:
73213253934900890693392193153744191297970770141376366331034362810150418276824580197371257112553772665618056230236107226590464390210289236375958798503605476114216226774127364770484876376234638558009314571492010697667283938568229733935849989248854812448768945542843842293568454189451992876850854311570247002443

If a and b are co-prime, extended Euclid algorithm finds x and y such that
x a + y b == 1
but either x or y may be negative. For y = inverse of b modulo a,
if y < 0 then y = y + a,
which will convert y to a proper value modulo a (note my prior comment).
The wiki example finds t = inverse of a modulo n, and has the same check:
if t < 0 then t = t + n
http://en.wikipedia.org/wiki/Extended_Euclidean_algorithm#Modular_integers

Related

How to find remainder of a double in C? Modulo only works for integers

This is what I've found so far online,
int main(void)
{
long a = 12345;
int b = 10;
int remain = a - (a / b) * b;
printf("%i\n", remain);
}
First I wonder how the formula works. Maybe i cant do math, but the priority of operations here seems a bit odd. If i run this code the expected answer of 5 is printed. But I dont get how (a / b) * b doesn't cancel out to 'a' leading to a - a = 0.
Now, this only works for int and long, as soon as double are involved it doesn't work anymore. Anyone might tell me why? Is there an alternative to modulo that works for double?
Also I'm not sure if i understand up to what value a long can go, i found online that the upper limit was 2147483647 but when i input bigger numbers such as the one in 'a' the code runs without any issue up to a certain point...
Thanks for your help I'm new to coding and trying to learn!
Given two double finite numbers x and y, with y not equal to zero, fmod(x, y) produces the remainder of x when divided by y. Specifically, it returns x − ny, where n is chosen so that x − ny has the same sign as x and is smaller in magnitude than y. (So, if x is positive, 0 ≤ fmod(x, y) < x, and, if x is negative, x < fmod(x, y) ≤ 0.)
fmod is declared in <math.h>.
A properly implemented fmod returns an exact result; there is no floating-point error, since the specified result is always representable.
The C standard also specifies remquo to return the remainder and some low bits (at least three) of the quotient n and remainder with a variation on the definition of the remainder. It also specifies variants of these functions for float and long double.
Naive implementation. Limited range. Adds additional floating point imprecisions (as it does some arithmetic)
double naivemod(double x)
{
return x - (long long)x;
}
int main(void)
{
printf("%.50f\n", naivemod(345345.567567756));
printf("%.50f\n", naivemod(.0));
printf("%.50f\n", naivemod(10.5));
printf("%.50f\n", naivemod(-10.0/3));
}

Bézout's identity, finding integers x and y such that ax+by = gcd(a,b)

The gcd function in the following code is given in the book Programming Challenges by Steven Skiena as a way of finding integers x and y such that ax+by = gcd(a,b). For example, given that a = 34398 and b = 2132 (whose gcd = 26), the algorithm the code below is meant to execute should return 34398 × 15 + 2132 × −242 = 26. The algorithm to find x and y is based on the base case y = 1 and x = 0 since a * 1+0*0 = gcd(a,0) and according to Euclid's algorithm gcd(34398, 2132) reduces to gcd(gcd(34398, 2132),0) or gcd(26,0). Euclid's algorithm can be applied backwards to find that 34398 × 15 + 2132 × −242 = 26.
#include <stdio.h>
#include <math.h>
int main() {
gcd(34398, 2132, 0, 1);
/* Find the gcd(p,q) and x,y such that p*x + q*y = gcd(p,q) */
long gcd(long p, long q, long *x, long *y)
{
long x1,y1; /* previous coefficients */
long g; /* value of gcd(p, q) */
if (q > p) return(gcd(q, p, y, x));
if (q == 0) {
*x = 1;
*y = 0;
return(p);
}
g = gcd(q, p % q, &x1, &y1);
*x = y1;
*y = (x1 - floor(p / q) * y1);
return(g);
}
return 0;
}
How do you test this code? The required input seems to be the p, q, and the base case x and y values but when I run the program below using the line of code gcd(34398, 2132, 0, 1); there is a runtime error message that states 'conflicting types for gcd'.
The declaration long gcd(long p, long q, long *x, long *y) says the last two parameters of gcd are pointers. So you must pass it pointers to existing long; you cannot pass it values such as 0 and 1.
To do that, define two long objects in main, possibly also called x and y, such as long x = 0, y = 1;. Then pass pointers to those objects to gcd, as with gcd(34398, 2132, &x, &y);.
Further, you must put the declaration of gcd before any use of it.
Defining gcd inside main is an extension to the C standard. That extension is useful in situations where the nested function needs certain context from its containing function. There is no need for that here, so the function should be defined in the ordinary way. Move the entire definition of gcd from inside main to before main.
There is no reason to use floor in floor(p / q), because p and q have integer type and integer division will be performed. There will be no fraction part for floor to remove. It can actually make the result wrong if the double type has less precision than the long type. So just use p/q.
There is also no reason to use recursion in this code. It is wasteful and not pedagogical in this situation. (Referring to the book Programming Challenges, the author says “Euclid’s algorithm is recursive…” However, I have a 2003 English translation of Euclid’s Elements, circa 300 BCE. Looking at Euclid’s GCD algorithm in Book VII, Propositions 1 and 2, I would say it is iterative, not recursive. In its cumbersome way, as seen through modern eyes, it describes doing things repeatedly, not reapplying the whole algorithm de novo.)

Is it possible to implement the extended euclidean algorithm with unsigned machine words?

I'm trying to find a way to implement EEA using uint64_t in C, on a system that will not support 128-bit integers. The problem is that it seems like there is always a case where some variable or another will overflow, generating incorrect results.
I know it can be done in /signed/ machine words, and there are plenty of answers on here and elsewhere that give pseudocode for this. Can it be done with unsigned and no overflow? Or do you need to have a larger integer size available?
The coefficients in the Euclidian algorithm alternate in sign (after the initial zeros vanish), so we can compute them using magnitudes only and reconstructing the sign at the end from the iteration parity.
The extended Euclidian algorithm finds the multiplicative inverses a and b of positive relatively prime integers u and v with respect to each other. That is, we find a and b such that a•u is congruent to 1 modulo v and b•v is congruent to 1 modulo u. We start with two equations:
u = 1•u + 0•v.
v = 0•u + 1•v.
Then the algorithm is:
Let x and y be the left sides of the latest two equations (y is later).
If y is 1, we are done. The coefficients of u and v on the right side are the inverses of u and v, respectively.
Otherwise, let q be the integer quotient x divided by y. Append a new equation that equals the earlier equation minus the later equation times q.
This implements the Euclidean algorithm on the left side of the equation, so we know it terminates in 1 for relatively prime u and v. Then the last equation has the form:
1 = a•u + b•v.
In this, it is clear a is a multiplicative inverse of u modulo v and b is a multiplicative inverse of b modulo u.
Observe that in the third equation, the coefficient of u will be 1−0•q. Thus, it will be positive. And the coefficient of v will be 0−1•q. Thus, it will be negative. In the fourth equation, the coefficient of u will be positive. From that point on, we are always subtracting a negative number from a positive number or a positive number from a negative number, and thus we alternate signs.
In the nth equation, the coefficient of u is non-negative if n is odd and non-positive if n is even, and vice-versa for the coefficient of v.
Therefore, we can implement this with unsigned arithmetic by keeping only the magnitudes of the coefficients:
Given magnitude g of a known-non-negative coefficient and a magnitude h of a known-non-positive coefficient, calculate the new magnitude as g+h•q.
Given magnitude g of a known-non-positive coefficient and a magnitude h of a known-non-negative coefficient, calculate the new magnitude as g+h•q.
Example for 13 and 10:
13 = 1•13 + 0•10.
10 = 0•13 + 1•10.
Quotient for 13/10 is 1. Compute 13−1•10 = 3, 1+0•1 = 1, 0+1•1 = 1. This gives:
3 = 1•13 − 1•10. (Sign is known implicitly, not computed.)
Quotient for 10/3 is 3. Compute 10−3•3 = 1, 0+1•3 = 3, 1+1•3 = 4. This gives:
1 = −3•13 + 4•10.
At this point, whatever variable we are using to hold the coefficient of u (13) contains 3, but we know it is negative because we are in an even iteration (the fourth). So an inverse of u is −3. If desired, we can add u (calculated as u minus the stored magnitude) to get a positive result.
I have proven these calculations never exceed v for the coefficient of u or u for the coefficient of v but do not have access to that proof. (It is embedded in source code for a previous employer.)
Eric Postpischil is absolutely right, but the answer is hard to read, especially if you are looking for code that just works, so here you go:
template<typename T>
typename std::enable_if<std::is_unsigned<T>::value,tuple<T,T>>::type
constexpr extended_euclidean(const T a, const T b)
{
T r0 = a;
T r1 = b;
T s0 = 1;
T s1 = 0;
T t0 = 0;
T t1 = 1;
size_t n = 0;
while (r1) {
T q = r0 / r1;
r0 = r0>q*r1?r0-q*r1:q*r1-r0; swap(r0,r1);
s0 = s0+q*s1; swap(s0,s1);
t0 = t0+q*t1; swap(t0,t1);
++n;
}
// gcd = r0
if (n%2) s0=b-s0;
else t0=a-t0;
return tuple<T,T>({s0,t0});
}
So basically we are doing the standard euclidean algorithm, but when computing the remainders we only care about the magnitude and when updating the coefficients we can just add. The sign of the magnitude needs to be fixed in the end using the parity, using a counter n.

Computing fractional exponents in C

I'm trying to evaluate a^n, where a and n are rational numbers.
I don't want to use any predefined functions like sqrt() or pow()
So I'm trying to use Newton's Method to get an approximate solution using this approach:
3^0.2 = 3^(1/5) , so if x = 3^0.2, x^5 = 3.
Probably the best way to solve that (without a calculator but still
using the basic arithmetic operations) is to use "Newton's method".
Newton's method for solving the equation f(x)= 0 is to set up a
sequence of numbers xn defined by taking x0 as some initial "guess"
and then xn+1= xn- f(xn/f '(xn) where f '(x) is the derivative of f.
Posted on physicsforums
The problem with that method is that if I want to compute 5.2^0.33333, I'll need to find the roots for this equation x^10000 - 5.2^33333 = 0. I end up with huge numbers, and get inf and nan errors most of the time.
Can someone give me advice on how to solve this problem? Or, can someone provide another algorithm to compute a^n?
It seems your task is to calculate
⎛ xN ⎞(aN / aD)
⎜⎼⎼⎼⎼⎟ where xN,xD,aN,aD ∈ ℤ, xD,aD ≠ 0
⎝ xD ⎠
using only multiplications, divisions, additions, and subtractions, with Newton's method as the suggested method to implement.
The equation we're trying to solve (for y) is
(aN / aD)
y = (xN / xD) where y ∈ ℝ
Newton's method finds a root of a function. If we want to use it to solve the above, we substract the right side from the left side, to get a function whose zero gives us the y we want:
(aN/aD)
f(y) = y - (xN/xD) = 0
Not much help. I guess this is as far as you got? The point here is to not form that function just yet, because we don't have a way to calculate a rational power of a rational number!
First, let's decide that aD and xD are both positive. We can do that simply by negating both aN and aD if aD was negative (so sign of aN/aD does not change), and negating both xN and xD if xD was negative. Remember, by definition neither xD or aD is zero. Then, we can simply raise both sides to the aD'th power:
aD aN aN aN
y = (xN / xD) = xN / xD
We can even eliminate the division by multiplying both sides by the last term:
aD aN aN
y × xD = xN
Now, this looks quite promising! The function we get from this is
aD aN aN
f(y) = y xD - xN
Newton's method also requires the derivative, which is obviously
f(y) aD aN
⎼⎼⎼⎼ = df(y) = y xD y / aD
dy
Newton's method itself relies on iterating
f(y)
y = y - ⎼⎼⎼⎼⎼⎼
i+1 i df(y)
If you work out the math, you'll find that the iteration is just
aD
y[i] y[i] xN
y[i+1] = y[i] - ⎼⎼⎼⎼ + ⎼⎼⎼⎼⎼⎼⎼⎼⎼⎼⎼⎼⎼⎼
aD aD aN
aD y[i] xD
You don't need to keep all the y values in memory; it is enough to remember the last one, and stop iterating when their difference is small enough.
You do still have exponentiation above, but now they are integer exponentiation only, i.e.
aD
xN = xN × xN × .. × xN
╰───────┬───────╯
aD times
which you can do very simply, for example just by multiplying the argument by itself the desired number of times, e.g. in C,
double ipow(const double base, const int exponent)
{
double result = 1.0;
int i;
for (i = 0; i < exponent; i++)
result *= base;
return result;
}
There are more efficient methods to do integer exponentiation, but the above function should be perfectly acceptable for this.
The final problem is to pick the initial y so that you get convergence. You cannot use 0, because (a power of) y is used as a denominator in the division; you'd get division by zero error. Personally, I'd check whether the result ought to be positive or negative, and smaller than or greater than one in magnitude; two rules overall to pick a safe initial y.
Questions?
You can use the generalized binomial theorem. Substitute y=1 and x=a-1. You would want to truncate the infinite series after enough terms, based on the desired accuracy. To be able to link number of terms to accuracy, you would need to ensure that the x^r terms are decreasing in absolute value. So, depending on the value of a and n, you should apply the formula to compute one of a^n and a^(-n) and use that to get your desired result.
A solution for raising an integer number to a power is:
int poweri (int x, unsigned int y)
{
int temp;
if (y == 0)
return 1;
temp = poweri (x, y / 2);
if ((y % 2) == 0)
return temp * temp;
else
return x * temp * temp;
}
However, the square root doesn't provide as clean of a closed solution. There is a good bit of background to be found at wikipedia-square root and at Wolfram Mathworks Square Root Algorithms Both provide several methods that will meet your needs, you just have to choose the one that fits your purpose.
With slight modification, this routine from wikipedia (modified to return the square root and refine accuracy) returns a surprisingly accurate square root. Yes, there will be howls about the use of a union, and it is only valid where integer and float storage are equivalent, but if you are hacking your own square root, this is relatively efficient:
float sqrt_f (float x)
{
float xhalf = 0.5f*x;
union
{
float x;
int i;
} u;
u.x = x;
u.i = 0x5f3759df - (u.i >> 1);
/* The next line can be repeated any number of times to increase accuracy */
// u.x = u.x * (1.5f - xhalf * u.x * u.x);
int i = 10;
while (i--)
u.x *= 1.5f - xhalf * u.x * u.x;
return 1.0f / u.x;
}

Reverse Modulus Operator with given condition

I have an equation:
x^2 mod p = z ;
p and z are given. x,p and z are positive integers and MAX value of x is given (say M). p is prime. How can i calculate (multiple possible values) x when p and z are known ?
UPDATE:
I found solution here:
https://math.stackexchange.com/questions/848062/reverse-modulus-operator-with-given-condition/848106#848106
if x^2 mod p = z
then x^2 = n*p + z for some integer n
with p and z known, substitute integer values for n to find x
I don't why Santosh was downvoted,but his reasoning is correct!
As x^2 mod p=z --->> x^2=n*p+z // for some integer n.
As you have p and z as known in your hands,you can individually check if x^2 mod p=z as shown below in the code and then find x(or rather equate the value of x) :-
public static void main(String[] args) { //main-method
int x,p,z,xMAX=10; // as per your condition
p=13; // assigned p a prime positive integer value
z=10; // assigned z a positive integer value
for(x=0;x<=xMAX;x++){
int sq=(int)Math.pow(x,2); // squrare of x for each loop
if(sq%p==z){ // comparing square-value modulus prime value with value of z to be equal
System.out.println("One value of x possible is "+x); // if matches,you have one solution
}
else continue;
}
}
Sorry as the code is in Java,but I have mentioned comments in the code to identify each section. Also,this is very complicated algorithm as one can have a better algorithm for it,I guess! But,the output is working fine and is correct!
Output as per code :-
One value of x possible is 6
One value of x possible is 7

Resources