mod (%) of two large numbers without using java.math.BigInteger - java

I have to multiply two large numbers like x and y and then find the mod of result by p without using BigIntegerlike :
public static char[] x = {'1','1','5','7','9','2','0','8','9','2','3','7','3','1','6','1','9','5','4','2','3','5','7','0','9','8','5','0','0','8','6','8','7','9','0','7','8','5','3','2','6','9','9','8','4','6','6','5','6','4','0','5','6','4','0','3','9','4','5','7','5','8','4','0','0','7','9','0','8','8','3','3','7','6','6','4','4','7'};
public static char[] y = {'1','1','5','7','9','2','0','8','9','2','3','7','3','1','6','1','9','5','4','2','3','5','7','0','9','8','5','0','0','8','6','8','7','9','0','7','8','5','3','2','6','9','9','8','4','6','6','5','6','4','0','5','6','4','0','3','9','4','4','3','7','4','8','7','3','8','7','4','7','3','1','9','0','6','9','7','4','3'};
public static char[] p = {'1','1','5','7','9','2','0','8','9','2','3','7','3','1','6','1','9','5','4','2','3','5','7','0','9','8','5','0','0','8','6','8','7','9','0','7','8','5','3','2','6','9','9','8','4','6','6','5','6','4','0','5','6','4','0','3','9','4','5','7','5','8','4','0','0','7','9','0','8','8','3','4','6','7','1','6','6','3'};
I find out how to multiply x and y but I don't know how to compute mod of two large numbers
Can anyone help me?

Can you compare x and y?
If you can compare them, you can easily implement mod algorithm.
Pseudo Code
function mod(a , b) {
while( a > b ) { a = a - b; }
return a;
}
I dont know java, this is just pseudo code for algorithm.
But if you have implemented subtract and compare functions, you can use them here.

Related

How to calculate (a^b^c^d) mod 10^9+7?

i tried using this.
import java.io.*; // for handling input/output
import java.util.*; // contains Collections framework
// don't change the name of this class
// you can add inner classes if needed
class Main {
public static void main (String[] args) {
Scanner s=new Scanner(System.in);
int m=1000000007;
int a=s.nextInt();
int b=s.nextInt();
int c=s.nextInt();
int d=s.nextInt();
long temp1=power(c,d)%m;
long temp2= power(b,temp1)%m;
long result=power(a,temp2)%m;
System.out.println(result);
}
public static long power(int x, long n){
int m=1000000007;
if(n==0){
return 1;
}
if(n==1){
return x;
}
if(n%2==0){
return (power(x,n/2)*power(x,n/2))%m;
}else {
return ((power(x,n/2)*power(x,n/2))%m * x)%m;
}
}
}
but problem is when i increase size of a b c d then its showing TLE.
like for a=2 b=2 c=2 d=2 its giving output 65536 but when i take a=12 b=12 c=12 d=12 output should be 322269119 but using this it is showing Time limit exceed error. anyone can explain how to do this type of qurstion where it said that output value will be large so print is after doing mod 10^9+7.
Edit: a b c d values can be different.
The TLE is due to power recursively calling itself twice per invocation, so it expands to a full binary tree of calls (size: n) instead of into a nice linear chain of calls (length: log(n)) which is how Exponentiation by Squaring is supposed to work. In other words, it's exponentially slower than it needs to be, and for a very boring reason. Easy fix:
public static long power(int x, long n){
int m=1000000007;
if(n==0){
return 1;
}
if(n==1){
return x;
}
long p = power(x,n/2);
if(n%2==0){
return p * p % m;
}else {
return (p * p % m) * x % m;
}
}
But there is also a "math bug" in your program: abcd mod n is not equivalent to a^(b^(c^d mod n) mod n) mod n. Modular addition and multiplication work that way, but exponentiation has a different kind of periodicity.
Just using big integers naively is not sufficient, 12^12^12 would be a 4TB BigInteger, even on a computer that could handle that, computing or using such a physically large number would just take too long. But you can use Euler's theorem, and compute 12^12^12 mod φ(n). 12^12 is no big deal it even fits in a long, then 12 to the power of that long can be a modexp again but modulo φ(1E9+7) which is 1E9+6. For slightly larger c and d, c^d can also be computed as a BigInteger, as long as it isn't too big.
When c or d are so large that c^d is a problem even with BigIntegers, you can use more tricks to compute b^c^d mod φ(n) without the "full" c^d. Unfortunately Euler's theorem is not applicable to the "inner" exponentiation because the GCD of the modulus and the base may not be 1 (and isn't 1 in the example with the twelves), but there is a more complex expression that works in that case.

Shuffling through all the points in a 3-dimensional space without storing all possible coordinates

I'm programming a 3-dimensional cellular automata. The way I'm iterating through it right now in each generation is:
Create a list of all possible coordinates in the 3D space.
Shuffle the list.
Iterate through the list until all coordinates have been visited.
Goto 2.
Here's the code:
I've a simple 3 integer struct
public class Coordinate
{
public int x;
public int y;
public int z;
public Coordinate(int x, int y, int z) {this.x = x; this.y = y; this.z = z;}
}
then at some point I do this:
List<Coordinate> all_coordinates = new ArrayList<>();
[...]
for(int z=0 ; z<length ; z++)
{
for(int x=0 ; x<diameter ; x++)
{
for(int y=0 ; y<diameter ; y++)
{
all_coordinates.add(new Coordinate(x,y,z));
}
}
}
and then in the main algorithm I do this:
private void next_generation()
{
Collections.shuffle(all_coordinates);
for (int i=0 ; i < all_coordinates.size() ; i++)
{
[...]
}
}
The problem is, once the automata gets too large, the list containing all possible points gets huge. I need a way to shuffle through all the points without having to actually store all the possible points in memory. How should I go about this?
One way to do this is to start by mapping your three dimensional coordinates into a single dimension. Let's say that your three dimensions' sizes are X, Y, and Z. So your x coordinate goes from 0 to X-1, etc. The full size of your space is X*Y*Z. We'll call that S.
To map any coordinate in 3-space to 1-space, you use the formula (x*X) + (Y*y) + z.
Of course, once you generate the numbers, you have to convert back to 3-space. That's a simple matter of reversing the conversion above. Assuming that coord is the 1-space coordinate:
x = coord/X
coord = coord % X
y = coord/Y
z = coord % Y
Now, with a single dimension to work with, you've simplified the problem to one of generating all the numbers from 0 to S in pseudo-random order, without duplication.
I know of at least three ways to do this. The simplest uses a multiplicative inverse, as I showed here: Given a number, produce another random number that is the same every time and distinct from all other results.
When you've generated all of the numbers, you "re-shuffle" the list by picking a different x and m values for the multiplicative inverse calculations.
Another way of creating a non-repeating pseudo-random sequence in a particular range is with a linear feedback shift register. I don't have a ready example, but I have used them. To change the order, (i.e. re-shuffle), you re-initialize the generator with different parameters.
You might also be interested in the answers to this question: Unique (non-repeating) random numbers in O(1)?. That user was only looking for 1,000 numbers, so he could use a table, and the accepted answer reflects that. Other answers cover the LFSR, and a Linear congruential generator that is designed with a specific period.
None of the methods I mentioned require that you maintain much state. The amount of state you need to maintain is constant, whether your range is 20 or 20,000,000.
Note that all of the methods I mentioned above give pseudo-random sequences. They will not be truly random, but they'll likely be close enough to random to fit your needs.

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.

Java math function to convert positive int to negative and negative to positive?

Is there a Java function to convert a positive int to a negative one and a negative int to a positive one?
I'm looking for a reverse function to perform this conversion:
-5 -> 5
5 -> -5
What about x *= -1; ? Do you really want a library function for this?
x = -x;
This is probably the most trivial question I have ever seen anywhere.
... and why you would call this trivial function 'reverse()' is another mystery.
Just use the unary minus operator:
int x = 5;
...
x = -x; // Here's the mystery library function - the single character "-"
Java has two minus operators:
the familiar arithmetic version (eg 0 - x), and
the unary minus operation (used here), which negates the (single) operand
This compiles and works as expected.
Another method (2's complement):
public int reverse(int x){
x~=x;
x++;
return x;
}
It does a one's complement first (by complementing all the bits) and then adds 1 to x. This method does the job as well.
Note: This method is written in Java, and will be similar to a lot of other languages
No such function exists or is possible to write.
The problem is the edge case Integer.MIN_VALUE (-2,147,483,648 = 0x80000000) apply each of the three methods above and you get the same value out. This is due to the representation of integers and the maximum possible integer Integer.MAX_VALUE (-2,147,483,647 = 0x7fffffff) which is one less what -Integer.MIN_VALUE should be.
Yes, as was already noted by Jeffrey Bosboom (Sorry Jeffrey, I hadn't noticed your comment when I answered), there is such a function: Math.negateExact.
and
No, you probably shouldn't be using it. Not unless you need a method reference.
original *= -1;
Simple line of code, original is any int you want it to be.
Necromancing here.
Obviously, x *= -1; is far too simple.
Instead, we could use a trivial binary complement:
number = ~(number - 1) ;
Like this:
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
int iPositive = 15;
int iNegative = ( ~(iPositive - 1) ) ; // Use extra brackets when using as C preprocessor directive ! ! !...
System.out.println(iNegative);
iPositive = ~(iNegative - 1) ;
System.out.println(iPositive);
iNegative = 0;
iPositive = ~(iNegative - 1);
System.out.println(iPositive);
}
}
That way we can ensure that mediocre programmers don't understand what's going on ;)
The easiest thing to do is 0- the value
for instance if int i = 5;
0-i would give you -5
and if i was -6;
0- i would give you 6
You can use the minus operator or Math.abs. These work for all negative integers EXCEPT for Integer.MIN_VALUE!
If you do 0 - MIN_VALUE the answer is still MIN_VALUE.
For converting a negative number to positive. Simply use Math.abs() inbuilt function.
int n = -10;
n = Math.abs(n);
All the best!
In kotlin you can use unaryPlus and unaryMinus
input = input.unaryPlus()
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-plus.html
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-int/unary-minus.html
You can use Math:
int x = Math.abs(-5);

Implement “intersection” method using java

How can i implement “intersection” method using java by recieve 2 integer parameters and return integer intersection point.
Maybe this could help
Perhaps you mean bitwise intersection, in which case you are looking for the bitwise-and operator (&). If so, you use it like this:
int x = int1 & int2;
If what you want is a function that takes two 'line' objects and returns a coordinate where they intersect, i suggest looking at the formula here
http://en.wikipedia.org/wiki/Line-line_intersection
and doing
func(line a, lineb)
{
x1 = a.coord1.x;
y1 = a.coord1.y;
x2 = a.coord2.x;
y2 = a.coord2.y;
//do math and code here
return line(coord(x1new,y1new),coord(x2new,y2new));
}
If this isn't what you wanted, please refer to Ido's comment :p
If you want to be really lazy why don't you just use the line2d library. http://download.oracle.com/javase/1.4.2/docs/api/java/awt/geom/Line2D.html It can find the intersect and many other things that have to do with a 2d line already built in.
As far as I can see, if you use two integer parameters, all you really need to do is average the two numbers, and that's the midpoint (intersection, I guess?)
int intersect(int a, int b) {
return ((a + b) / 2);
}
Otherwise, if you are looking for bitwise intersection, you would used the bitwise-AND operator - &. Here's an example:
int intersect(int a, int b) {
return (a & b);
}

Categories