Using Euclidean algorithm in java - java

If I have x= 11 and y = 6 and I want to calculate
(w*x)mod(y) = 1 . In other words how can I calculate the number that if multiplied by 11 and then modulus 6 the result 1. In this case w should be equal to 5.
Is there anyway I can calculate the w in a method using Euclidean algorithm in java?
Thank you!

There is a theorem that says that the linear congruence a * x = b (mod n), where a, b, and n are integers, has a solution if and only if gcd(a, n) = 1.
Since gcd(11,6) = 1, which is simply because 11 is a prime number, your equation is indeed solvable.
To answer the question, no, you cannot solve the linear congruence using Euclid's algorithms---however, you can do that using extended Euclid's algorithm---, but you can use it so verify that the equation is solvable.
Once you find that gcd(a,n)=1, you compute the solution as x = b*r mod n, where r = a^-1 (mod n). To compute the inverse of a, which here we denoted r, you can use the extended Euclidean algorithm (abbreviated EEA).
If gcd(a,n)=1, then EEA, given a and n, computes r and s such that a*r + n*s = 1. We claim that r is the inverse of a modulo n. Once you have r, you compute x = b * r mod n.
These algorithms are nicely described in the book Introduction to Algorithm by Cormen et al.

Related

Pollard Rho can't find factor

So I am attempting to create a Pollard's Rho Factoring Algorithm in Java using the BigInteger class to support very large integers. The code mostly works but cannot find a factor for 4 or 8 (which should be 2). Currently I have capped it to cycle through the algorithm 10,000,000 times and still it can't find 2 as a factor. a is generated randomly (limited between 0 and 1000). Is this just a flaw in the Pollard Rho Algorithm or is there a mistake somewhere in the implementation?
The n being passed is 4
The initial a is calculated as a random the same way in the below code, between 0 and 1000
The sqrt(n) method returns the floor of the square root of n (in this case sqrt(sqrt(4)) = 1
I printed count at the end to make sure it was actually iterating how many times it was supposed to.
private static BigInteger PollardRho (BigInteger a, BigInteger n) {
BigInteger gcd = BigInteger.ZERO;
BigInteger Tort = a;
BigInteger Hare = a;
BigInteger count = BigInteger.ZERO;
BigInteger iterationLim = (sqrt(sqrt(n))).multiply(BigInteger.valueOf(10000000));
while (count.compareTo(iterationLim)!=0)
//makes sure that the algorithm does not surpass (4th root of n)*10000000 iterations.
{
Tort = ((Tort.pow(2)).add(BigInteger.ONE)).mod(n);
//System.out.println("Tort: "+Tort);
Hare = (((Hare.pow(2)).add(BigInteger.ONE).pow(2)).add(BigInteger.ONE)).mod(n);
//System.out.println("Hare: "+Hare);
gcd = (Tort.subtract(Hare)).gcd(n);
//System.out.println("gcd: "+gcd);
if (gcd.compareTo(BigInteger.ONE) != 0 && gcd.compareTo(n) != 0)
{
// System.out.println("took if, gcd = "+gcd);
return gcd;
}
if (gcd.compareTo(n) == 0)
{
a = (BigInteger.valueOf((long) (1000*Math.random())));
Tort = a;
Hare = a;
}
count = count.add(BigInteger.ONE);
}
System.out.println(count);
return n;
}
Pollard's Rho method usually can only split numbers composed of different primes. It fails most of the time for numbers that are prime powers. 4 and 8 are powers of a single prime 2 and therefore unlikely to be split by this method.
The method works by iterating a random function f(x) mod n, in this case f(x) = x^2+1 is used, but other functions work as well. The trick is that f(x) mod p where p is a prime factor of n enters a cycle after a different number of iterations for different primes. So f(x) mod p1 may already be in a cycle, f(x) mod p2 not yet. The gcd calculation is then able to find the factor p1.
It is btw. very easy to check if a number is a proper power of an integer. Just calculate the 2nd, 3rd, 4th, ... root and check if it is an integer.

Algorithm for adding two numbers to reach a value

I have a homework assignment that asks of me to check, for any three numbers, a,b,c such that 0<=a,b,c<=10^16, if I can reach c by adding a and b to each other. The trick is, with every addition, their value changes, so if we add a to b, we would then have the numbers a and a+b, instead of a and b. Because of this, I realized it's not a simple linear equation.
In order for this to be possible, the target number c, must be able to be represented in the form:
c = xa + yb
Through some testing, I figured out that the values of x and y, can't be equal, nor can both of them be even, in order for me to be able to reach the number c. Keeping this in mind, along with some special cases involving a,b or c to be equal to zero.
Any ideas?
EDIT:
It's not Euclid's Algorithm, it's not a diophantine equation, maybe I have mislead you with the statement that c = xa + yc. Even though they should satisfy this statement, it's not enough for the assignment at hand.
Take a=2, b=3, c=10 for example. In order to reach c, you would need to add a to b or b to a in the first step, and then in the second step you'd get either : a = 2, b = 5 or a = 5, b = 3, and if you keep doing this, you will never reach c. Euclid's algorithm will provide the output yes, but it's clear that you can't reach 10, by adding 2 and 3 to one another.
Note: To restate the problem, as I understand it: Suppose you're given nonnegative integers a, b, and c. Is it possible, by performing a sequence of zero or more operations a = a + b or b = b + a, to reach a point where a + b == c?
OK, after looking into this further, I think you can make a small change to the statement you made in your question:
In order for this to be possible, the target number c, must be able to
be represented in the form:
c = xa + yb
where GCD(x,y) = 1.
(Also, x and y need to be nonnegative; I'm not sure if they may be 0 or not.)
Your original observation, that x may not equal y (unless they're both 1) and that x and y cannot both be even, are implied by the new condition GCD(x,y) = 1; so those observations were correct, but not strong enough.
If you use this in your program instead of the test you already have, it may make the tests pass. (I'm not guaranteeing anything.) For a faster algorithm, you can use Extended Euclid's Algorithm as suggested in the comments (and Henry's answer) to find one x0 and y0; but if GCD(x0,y0) ≠ 1, you'd have to try other possibilities x = x0 + nb, y = y0 - na, for some n (which may be negative).
I don't have a rigorous proof. Suppose we constructed the set S of all pairs (x,y) such that (1,1) is in S, and if (x,y) is in S then (x,x+y) and (x+y,y) are in S. It's obvious that (1,n) and (n,1) are in S for all n > 1. Then we can try to figure out, for some m and n > 1, how could the pair (m,n) get into S? If m < n, this is possible only if (m, n-m) was already in S. If m > n, it's possible only if (m-n, n) was already in S. Either way, when you keep subtracting the smaller number from the larger, what you get is essentially Euclid's algorithm, which means you'll hit a point where your pair is (g,g) where g = GCD(m,n); and that pair is in S only if g = 1. It appears to me that the possible values for x and y in the above equation for the target number c are exactly those which are in S. Still, this is partly based on intuition; more work would be needed to make it rigorous.
If we forget for a moment that x and y should be positive, the equation c = xa + yb has either no or infinitely many solutions. When c is not a multiple of gcd(a,b) there is no solution.
Otherwise, calling gcd(a,b) = t use the extended euclidean algorithm to find d and e such that t = da + eb. One solution is then given by c = dc/t a + ec/t b.
It is clear that 0 = b/t a - a/t b so more solutions can be found by adding a multiple f of that to the equation:
c = (dc + fb)/t a + (ec - af)/t b
When we now reintroduce the restriction that x and y must be positive or zero, the question becomes to find values of f that make x = (dc + fb)/t and y = (ec - af)/t both positive or zero.
If dc < 0 try the smallest f that makes dc + fb >= 0 and see if ec - af is also >=0.
Otherwise try the largest f (a negative number) that makes ec - af >= 0 and check if dc + fb >= 0.
import java.util.*;
import java.math.BigInteger;
public class Main
{
private static boolean result(long a, long b, long c)
{
long M=c%(a+b);
return (M%b == 0) || (M%a == 0);
}
}
Idea:c=xa+by, because either x or y is bigger we can write the latter equation in one of two forms:
c=x(a+b)+(y-x)b,
c=y(a+b)+(x-y)a
depending on who is bigger, so by reducing c by a+b each time, c eventually becomes:
c=(y-x)b or c=(x-y)b, so c%b or c%a will evaluate to 0.

Find a sum equal or greater than given target using only numbers from set

Example 1:
Shop selling beer, available packages are 6 and 10 units per package. Customer inputs 26 and algorithm replies 26, because 26 = 10 + 10 + 6.
Example 2:
Selling spices, available packages are 0.6, 1.5 and 3. Target value = 5. Algorithm returns value 5.1, because it is the nearest greater number than target possible to achieve with packages (3, 1.5, 0.6).
I need a Java method that will suggest that number.
Simmilar algorithm is described in Bin packing problem, but it doesn't suit me.
I tried it and when it returned me the number smaller than target I was runnig it once again with increased target number. But it is not efficient when number of packages is huge.
I need almost the same algorithm, but with the equal or greater nearest number.
Similar question: Find if a number is a possible sum of two or more numbers in a given set - python.
First let's reduce this problem to integers rather than real numbers, otherwise we won't get a fast optimal algorithm out of this. For example, let's multiply all numbers by 100 and then just round it to the next integer. So say we have item sizes x1, ..., xn and target size Y. We want to minimize the value
k1 x1 + ... + kn xn - Y
under the conditions
(1) ki is a non-positive integer for all n ≥ i ≥ 1
(2) k1 x1 + ... + kn xn - Y ≥ 0
One simple algorithm for this would be to ask a series of questions like
Can we achieve k1 x1 + ... + kn xn = Y + 0?
Can we achieve k1 x1 + ... + kn xn = Y + 1?
Can we achieve k1 x1 + ... + kn xn = Y + z?
etc. with increasing z
until we get the answer "Yes". All of these problems are instances of the Knapsack problem with the weights set equal to the values of the items. The good news is that we can solve all those at once, if we can establish an upper bound for z. It's easy to show that there is a solution with z ≤ Y, unless all the xi are larger than Y, in which case the solution is just to pick the smallest xi.
So let's use the pseudopolynomial dynamic programming approach to solve Knapsack: Let f(i,j) be 1 iif we can reach total item size j with the first i items (x1, ..., xi). We have the recurrence
f(0,0) = 1
f(0,j) = 0 for all j > 0
f(i,j) = f(i - 1, j) or f(i - 1, j - x_i) or f(i - 1, j - 2 * x_i) ...
We can solve this DP array in O(n * Y) time and O(Y) space. The result will be the first j ≥ Y with f(n, j) = 1.
There are a few technical details that are left as an exercise to the reader:
How to implement this in Java
How to reconstruct the solution if needed. This can be done in O(n) time using the DP array (but then we need O(n * Y) space to remember the whole thing).
You want to solve the integer programming problem min(ct) s.t. ct >= T, c >= 0 where T is your target weight, and c is a non-negative integer vector specifying how much of each package to purchase, and t is the vector specifying the weight of each package. You can either solve this with dynamic programming as pointed out by another answer, or, if your weights and target weight are too large then you can use general integer programming solvers, which have been highly optimized over the years to give good speed performance in practice.

BigInteger most time optimized multiplication

Hi I want to multiply 2 big integer in a most timely optimized way. I am currently using karatsuba algorithm. Can anyone suggest more optimized way or algo to do it.
Thanks
public static BigInteger karatsuba(BigInteger x, BigInteger y) {
// cutoff to brute force
int N = Math.max(x.bitLength(), y.bitLength());
System.out.println(N);
if (N <= 2000) return x.multiply(y); // optimize this parameter
// number of bits divided by 2, rounded up
N = (N / 2) + (N % 2);
// x = a + 2^N b, y = c + 2^N d
BigInteger b = x.shiftRight(N);
BigInteger a = x.subtract(b.shiftLeft(N));
BigInteger d = y.shiftRight(N);
BigInteger c = y.subtract(d.shiftLeft(N));
// compute sub-expressions
BigInteger ac = karatsuba(a, c);
BigInteger bd = karatsuba(b, d);
BigInteger abcd = karatsuba(a.add(b), c.add(d));
return ac.add(abcd.subtract(ac).subtract(bd).shiftLeft(N)).add(bd.shiftLeft(2*N));
}
The version of BigInteger in jdk8 switches between the naive algorithm, The Toom-Cook algorithm, and Karatsuba depending on the size of the input to get excellent performance.
Complexity and actual speed are very different things in practice, because of the constant factors involved in the O notation. There is always a point where complexity prevails, but it may very well be out of the range (of input size) you are working with. The implementation details (level of optimization) of an algorithm also directly affect those constant factors.
My suggestion is to try a few different algorithms, preferably from a library that the authors already spent some effort optimizing, and actually measure and compare their speeds on your inputs.
Regarding SPOJ, don't forget the possibility that the main problem lies elsewhere (i.e. not in the multiplication speed of large integers).

Compute least squares using java

I am trying to find a java code to compute the least squares solution (x) in the Ax=b equation.
Suppose that
A = [1 0 0;1 0 0];
b = [1; 2];
x = A\b
returns the
x =
1.5000
0
0
I found Class LeastSquares,
public LeastSquares(double[] a, double[] b, int degree)
but in the input both A and B are one dimensional arrays, however, in above example, A is a matrix and B is an array.
In Class NonNegativeLeastSquares
public NonNegativeLeastSquares(int M, int N, double a[][],double b[])
A is a matrix and B is an array, but the description of the class says that it finds an approximate solution to the linear system of equations Ax = b, such that ||Ax - b||2 is minimized, and such that x >= 0. Which means that x must be always positive.
I need a similar class as NonNegativeLeastSquares, however with out the x>=0 constraint.
Could someone please help me?
thanks a lot.
See the Apache Commons Math library, specifically the SimpleRegression class.

Categories