Multiply arrays representing integers (Similar to BigInteger)? - java

Basically, the integer array (named digits of class BigInteger) is used to represent a single large integer. Up to this point, I have solved how to add-with-carry two of the arrays and also subtract-with-carry, but multiplication is giving me problems. Below is the code I have written:
public BigInteger multiply(BigInteger n) {
int carry = 0;
for(int i = n.digits.length - 1; i >= 0;i--) {
for(int j = this.digits.length - 1; i >= 0; i--) {
int val = (this.digits[i] * n.digits[j]) + carry;
this.digits[i] = val % 10;
carry = val / 10;
}
}//for
return this;
}
This code works as long as the invoking this is larger and the parameter n is a single digit. But as soon as n exceeds 1 digit, the code fails. I am at a loss, and guidance in the right direction would be appreciated.

Replace
for(int j = this.digits.length - 1; i >= 0; i--) {
with
for(int j = this.digits.length - 1; j >= 0; j--) {
You don't want to decrement i while iterating through the inner loop. After you make this correction, you should be good to go.

Related

how to check the divergence of 5 numbers in java

I have an array of five integers count[5] and I want to check if their difference is more than 3.
A brute force could be to do : if(count[5]-count[4])>3) ,if(count[5]-count[3]>3)
Is there a better way to do it ?
Not a very efficient way to do it, but
Integer min = Arrays.<Integer>asList(arr).stream().min(Comparator.naturalOrder());
Integer max = Arrays.<Integer>asList(arr).stream().min(Comparator.naturalOrder());
Integer spread = max - min;
will do the trick.
If the array is large, you'll want to do a reduce with a running tracker for min and max at the same time. Let me know if you really need that.
Here a Java code implementation:
public static boolean diff(int[] ar) {
boolean result = true;
for (int i = 0; i < ar.length; i++) {
for (int j = 0; j < ar.length; j++) {
if (Math.abs(ar[i] - ar[j]) > 3) {
result = false;
}
}
}
return result;
}
You can use for loop in case if the numbers in the array are to increase.
int[5] count = {1,2,3,4,5}
for(int i = 0; i < count.length; i++){
for(int j = 0; j < count.length; j++){
if(((count[i] - count[j]) > 3) || ((count[i] - count[j])<-3)){
//TODO
}
}
}

I need to use a nested for loop to display a 10 by 10 grid of randomly generated Xs and Os

int[][] grid = new int[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
// fill in
}
}
This is what I have so far. I know I need to add in Math.Random, then set X = 0 and O = 1. I'm just very lost and confused. I'm in no way a good java coder and for me this is too advanced.
char[][] grid = new char[10][10];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
grid[i][j] = "XO".charAt((int)Math.round(Math.random()));
}
}
String#charAt() gets a character by the index. (So 0 returns X and 1 returns O)
Math.random() returns a random Double between 0 and 1, and with Math.round() you round that number to the nearest whole number. (So either 0 or 1) which is used to give to the charAt() as parameter.
You do still need to cast the outcome of Math.round() as an int because it will return a long.

Java add matrix antidiagonal elements

I want to add a NxN matrix antidiagonal elements using a for loop in a java program.
This code (2 conditions) does not work because it always says when the loop is executed sum2=0.
for (int i=0,j=t-1; i<t && j==0; i++, j--) {
sum2 = sum2 + aNumber[i][j];
}
Instead this one (one condition) works well.
for (int i=0, j=t-1; i<t ; i++, j--) {
sum2 = sum2 + aNumber[i][j];
}
Why does not work the first code?
In your first example the loop ends as soon as j != 0, if t > 1 this means that it will end immediately, making no iterations at all.
Try something like this:
int maxIndex = matrix.length - 1;
int sum = 0;
for (int i = 0; i <= maxIndex; i++) {
sum += matrix[i][maxIndex - i];
}
This relies on the fact that the sum of the indexes of each antidiagonal element is exactly equal to N.

Raising a matrix to the power method JAVA

I am having a really hard time creating a method to raise a matrix to the power. I tried using this
public static int powerMethod(int matrix, int power) {
int temp = matrix ;
for (int i = power; i == 1; i--)
temp = temp * matrix ;
return temp ;
but the return is WAYYY off. Only the first (1,1) matrix element is on point.
I tried using that method in a main like so
// Multiplying matrices
for (i = 0; i < row; i++)
{
for (j = 0; j < column; j++)
{
for (l = 0; l < row; l++)
{
sum += matrix[i][l] * matrix[l][j] ;
}
matrix[i][j] = sum ;
sum = 0 ;
}
}
// Solving Power of matrix
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++)
matrixFinal[power][i][j] = Tools.powerMethod(matrix[i][j], power) ;
}
Where "power", "row", and "column" is an int that the user enters.
Any ideas how I can do this??
Thanks!!!
You have a lot of issues here.
First, your matrix squaring algorithm has a (common) error. You have:
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++) {
for (l = 0; l < row; l++) {
sum += matrix[i][l] * matrix[l][j] ;
}
matrix[i][j] = sum ;
sum = 0 ;
}
}
However, you need to store the result in a temporary second matrix, because when you do matrix[i][j] = sum, it replaces the value at that position with the output, then later results end up being incorrect. Also I suggest initializing sum to 0 first, since it appears you declare it outside of this loop, and initializing it first protects you against any arbitrary value sum may have before going into the loop. Furthermore, it is not immediately clear what you mean by row and column -- make sure you are iterating over the entire matrix. E.g.:
int temp[][] = new int[matrix.length];
for (i = 0; i < matrix.length; i++) {
temp[i] = new int[matrix[i].length];
for (j = 0; j < matrix[i].length; j++) {
sum = 0 ;
for (l = 0; l < matrix.length; l++) {
sum += matrix[i][l] * matrix[l][j] ;
}
temp[i][j] = sum ;
}
}
// the result is now in 'temp', you could do this if you wanted:
matrix = temp;
Note that matrix.length and matrix[i].length are fairly interchangeable above if the matrix is square (which it must be, in order to be multiplied by itself).
Secondly, your multiplication squares a matrix. This means if you repeatedly apply it, you keep squaring the matrix every time, which means you will only be able to compute powers that are themselves powers of two.
Your third issue is your final bit doesn't make much sense:
for (i = 0; i < row; i++) {
for (j = 0; j < column; j++)
matrixFinal[power][i][j] = Tools.powerMethod(matrix[i][j], power) ;
}
It's not immediately clear what you are trying to do here. The final part seems to be trying to raise individual elements to a certain power. But this is not the same as raising a matrix to a power.
What you need to do is define a proper matrix multiplication method that can multiply two arbitrary matrices, e.g.:
int[][] multiplyMatrices (int[][] a, int[][] b) {
// compute and return a x b, similar to your existing multiplication
// algorithm, and of course taking into account the comments about
// the 'temp' output matrix above
}
Then computing a power becomes straightforward:
int[][] powerMatrix (int[][] a, int p) {
int[][] result = a;
for (int n = 1; n < p; ++ n)
result = multiplyMatrices(result, a);
return result;
}
Why not just use Math.pow?
import java.lang.Math;
Then you just have to do
matrixFinal[power][i][j] = (int) Math.pow(matrix[i][j],power); //might have to cast this to an int

Big O analysis for this for loop

sum = 0;
for (i = 1; i <= n; i++) { //#1
for (j = 1; j <= i * i; j++) { //#2
if (j % i == 0) { //#3
for (k = 1; k <= j; k++) { //#4
sum++;
}
}
}
}
The above got me confusing
Suppose #1 runs for N times
#2 runs for N^2 times
#3 runs for N/c since for N inputs N/c could be true conditions
#4 runs for N times
Therefore roughly I could be looking at O(N^5) . I am not sure. Please help clarify.
EDIT I was wondering the runtime at the if(j%i==0). Since it takes N^2 inputs from its parent loop it could be doing (N^2)/c executions instead of N/c
I would say its O(N^4) as its the same as.
for (int i = 1; i <= n; i++) //#1 O(n ...
for (int j = i; j <= i * i; j+=i) //#2 ... * n ...
for (int k = 1; k <= j; k++) //#4 ... * n^2) as j ~= i^2
sum++;
or
public static void main(String... args) {
int n = 9000;
System.out.println((double) f(n * 10) / f(n));
}
private static long f(long n) {
long sum = 0;
for (long i = 1; i <= n; i++) //#1
for (long j = 1; j <= i; j++) //#2
sum += i * j; // # 4
return sum;
}
prints
9996.667534360826
which is pretty close to 10^4
#PeterLawrey did the math, here are benchmarks plotted on chart (my data set - n vs. execution time in microseconds).
Basically I run the code in question several times with different n input (X-axis). Then I divided average execution time by n^5, n^4 and n^3 functions and plotted that:
Full size image
Note that this is a logarithmic scale and that all functions were scaled to more-or-less be in the same range.
Guess what, avergae execution time t(n) divided by n^5 keeps getting decreasing, while t(n)/n^3 keeps growing. Only t(n)/n^4 is stabilizes when approaching infinity which proves that the average execution time is in fact O(n^4).
I think the answer, using Sigma notation, would be like the following:

Categories

Resources