Reverse Modulus Operator with given condition - c

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

Related

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.

Optimizing loop by using floating point value as loop counter

I need to execute a loop
while (X) do Y
for a N times, which is a large number. While Y, the loop body, is rather quick, the test X takes up about 70% of the runtime.
I can calculate the number of loop iterations N beforehand so instead of using X as the condition, a simple For-Loop would be possible.
for (i=1 to N) do Y
However, N might exceed the maximum value an integer can store on the machine, so this is not an option. As an alternative, I proposed to use a floating point variable F instead. As N is large, it is likely that F cannot be exactly equal to N. Thus, I calculate F to be the largest floating point number smaller than N. This allows me to run
for (i=1 to F) do Y
while (X) do Y
Most of the iterations will not need to test X everytime, only the last N-F do.
The question is: How would I implement a for-Loop from 1 to F? Simply increasing a counter or decreasing F by 1 in each step would not work, as the numerical error would grow too large. My current solution is:
for (while F > MAXINT)
for (i=1 to MAXINT)
do Y
F -= MAXINT
while (X) do Y
Is there a better way to solve this problem?
What do you mean by numerical error? Floating point counting is exact within its precision.
Here are the maximum values representable by integers exactly using the following data types:
uint32max = 4294967295
uint64max = 18446744073709551615
float32intmax = 16777216
float64intmax = 9007199254740992
Every integer from 0 to the max is exactly representable without numerical error.
As you can see, the largest count is available with uint64. Next comes float64, then uint32 and finally float32.
What happens when you increment uint32=4294967295 ? 0.
What happens when you increment float32=16777216 ? 16777216.
Which is the better behavior?
Have you thought about using a 2-dimensional loop? If N ism the maximum count for a 1-dimensional loop, then N x N is the maximum for a 2-dimensional loop, etc. so that if you maximum count is less than MAXUINT x MAXUINT, then decompose you number N such that:
N == M * MAXUINT + R;
where
M = N / MAXUINT;
R = N - M * MAXUINT;
then
for (i = M; i--;) for (j = MAXUINT; j--;) DoStuff();
for (i = R; i--;) DoStuff();
If MAXUINT*MAXUINT is not a large enough count for you, you can add 3-, 4-, ... -dimensional loops.

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

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

Why can we not use a variable as value of e in C

my compiler keeps giving me the error that I need to use a digit for this :
xek
where k is supposed to be the power for x using the exponent function e.g:
double x ;
for (int k = 1 ; k < 10; k++){
x = 4ek;
}
C has e notation for floating point numbers. It has special format specifier %e and %E just to print a floating point number in e notation. But neither the exponents nor mantissa can be variable. .
x = 4.0e7; is perfectly fine.
But to have variable power you need to use standard math library functions exp or pow.
x = pow(4, k);
or
x = 4 * exp(k);
The way you are using this in a loop, you can optimize it by keeping last calculated value this way: (Assuming x is initialized to 1 before loop begins.)
x = x * 4;
Every time loop runs x is multiplied by 4 hence basically at kth loop run x = 4*exp(k);.
You need
#include <math.h>
pow(x, k); // x to the power k
x * exp(k); // x multiplied by e to the k

Find subset of size k such that the minimum distance between values is maximum

Suppose i have an array which contain n integers .
How to find subset of size k such that the minimum distance between all pairs of integers in the subset is maximized , i mean they are at farthest distance .
example : array a[]={1,2,6,7,10} and k=3 ,
subset = {1,6,10} , the minimum distance is 4 between 10 and 6 .
Wrong subsets :
{1,7,10} , minimum distance is 3
{1,2,6} , minimum distance is 1
I came up with a solution :
1) sort array
2) select a[0] , now find ceil(a[0]+ x) = Y in array ....and then ceil(Y+ x) and so on k-1 times , also kth element will be a[n-1]
To find x :
dp[i,j] be the x for selecting j elements from first i elements .
Finally we want dp[n][k] which is x
But i am facing problem in finding x .
dp[i,j] = max( min( dp[k,j-1], dp[i]-A[k] ) )
over k=1 to i-1 , i=2 to n , j=2 to i
dp[i][1] = 0 over i = 1 to n
EDIT : I want to correct the dynamic programming solution , though i know x can be found out by binary searching over x .
UPDATE 2 : I have updated the code , but still not getting correct solution . Please point the error .
code : http://ideone.com/J5vvR9
UPDATE 3 : Thanks #Gassa , #Niklas B. and #Fallen for your answers !.
The base should be:
dp[i][1] = INFINITY for i = 1 to n
The reason being that minimum of an empty set is positive infinity.
In practice, any integer larger than the maximum possible a[i] - a[j] for some i and j will suffice as an INFINITY constant.
Additionally, the correct transition would be:
dp[i,j] = max{for k=1 to i-1} (min(dp[k,j-1], a[i]-a[k]))
I think there is no need in finding x if time allows to search for possible values of x. Just add the outer loop which will be a binary search on the answer (that is, the minimum distance, let us call it x).
Once x is fixed, you can greedily pick values starting from a[0]. The next selected value will be such a[i] that i is minimal and a[i] - a[0] >= x. The third one will be a[j] such that j is minimal and a[j] - a[i] >= x, and so on. If you are able to pick at least k values in this fashion, the actual answer is at least the current x; if not, the answer is less than x.
The total running time will be O (n log (C)) where C is the total number of possible values in the array. Say, if the integers in the array are from 0 to 1000000, C will be 1000001 and log (C) (rounded up) will be 20. First, you try x = 500000; if it fails, you are left with the range [0; 500000) for the answer; if not, with the range [500000; 1000000], etc.
Do a binary search over value of X. Then for each such x, write a DP/Greedy function that checks if there's an array with result(maximal distance between elements) more than or equal to X.
Correctness: If for any X, we can have M elements, such that minimum distance between them is greater than or equal to X, then for every x, x < X, at least this same array will server as result. And for any X, if there's no M elements, such that the minimum distance between the elements is greater than or equal to X, then for no x, x > X, M such elements are available. So we can binary search on X.

Resources