Variable changing value without changing it in the code - java

I am working on a custom numeric class for big numbers like BigInteger. I have to create this method where it finds the prime factorization of a given number. The problem lies in that method, when I assign the current value of a number and it doesn't find a factorization soon(like after 2 or 3 iterations) the value unexpectedly changes. Here's the code
public ArrayList<String> factors(){
ArrayList<String> pList = new ArrayList<>();
FedNumbers in = this;
FedNumbers d = new FedNumbers("2");
FedNumbers zero = new FedNumbers("0");
FedNumbers squared = d.product(d);
while(d.compareTo(in)<=0){
System.out.println(in);
if(in.divideR(d).compareTo(zero)==0){
pList.add(d.toString());
in=in.divideQ(d);
}
else{
d.inc();
squared=d.product(d);
}
}
pList.add(in.toString());
return pList;
}
divideQ is a method that divides and returns the coefficient and divideR one that returns its residue. The squared variable exists because of the assumption that I can found its factorization before sqrt(n). product multiplies two values and returns its result.
Here's the output for in being 161 at the beginning:
161
161
151
141
141
131
121
121
111
111
111
101
[1]
It never enter the iteration, I tried the division with residue and compareTo together in a tester alone and it worked, cant get why the in value changes suddenly after two iterations with no reason to.
That's the in value or the current value that I'm trying to factorize, same thing happens with many other numbers and every time I check its only the in value changing randomly. When I divide and use divideQ or divideR separate or multiply it always works perfectly. Thanks for the help in advance

I think the source of your problem is here:
FedNumbers in = this;
I may be wrong, but could it be that you think that this copies the current object, i.e., the one for which you call factors(), creating in as a new object?
This is not so. Copying a reference simply establishes another reference to the same object. Throughout factors, this and in refer to the same object.
It should not be too difficult to add a copy constructor to your code.

Related

Aproximation of log(10^k)

I am trying to find the result of log(10^k) , where k is big number like 10000. For example :
BigDecimal first = BigDecimal.TEN.pow(10000);
double result = Math.log(first.doubleValue());
However "result" becomes Infinity , however on wolphram approximates it to 23025.85.Any suggestion how to find the result? As a result the number with the first two digits after the decimal point are enough for me.
Use the fact that
log(10^k) = k*log(10)
So:
System.out.println(10000 * Math.log(10));
Prints:
23025.850929940458
The problem you are likely having, is that Wolphram is able to either hold the powered value or it is doing the log operation first.
When running this like your example, you will have an extremely large number that goes past the maximum value for a BigDecimal, which should result in an error or an "infinity", because it overflows the capability of the data type, I would suggest doing the operation the other way arround, perhaphs process the log first on a base 1 value for example and only then multiply it by whatever powered number you are tying to use.
See, there is a simple property of logarithms that you can use:
log(x^y) = y*log(x)
So what you can do is:
double y = y*log(x);
System.out.println(Math.round(y));
Hope this helps!

What datatype to use for 40 digit integers in java

For example
first number = 123456.....40 digits
second number = 123456.....40digits
Then I need to store the number
third = first * second;
after that I need to print third and again I need to perform operation like
fourth = third * third;
and print fourth. So how can I handle that much long integers which data type I need to use?
Use BigInteger class in java.math, then use BigInteger.multiply to multiply them together.
Check here for more on how to use it:
https://www.tutorialspoint.com/java/math/biginteger_multiply.htm
See this question its similar Arbitrary-precision arithmetic Explanation
the answer explain it quite good.
The basic is that you work with smaller parts. Just remember how you learned to work with big numbers in school (2-3 grade) you wrote down two numbers and
2351
*12
-----
4702
2351
------
28212
You just do small operations and store them somewhere you can put them in string or better in some array of integers. Where for example
number 123456789123456789 can be
number[0] = 6789
number[1] = 2345
number[3] = 7891
number[4] = 2345
number[5] = 1
String numberToShow = "";
for(int i = 0; i
There are some links for computer arighmetics
https://en.wikipedia.org/wiki/Category:Computer_arithmetic
and for adders
https://en.wikipedia.org/wiki/Category:Adders_(electronics)
In your computer you have basically also just some adders which can work only with some size of numbers and if you need to work with bigger you need to split it in smaller parts.
Some of this parts can be done parallel, so you can speed up your algorithm. These are usually more sophisticated.
But the basic principe is similar to working with big numbers on your primary school.

Last iteration of for loop not outputting

Forgive me if this is not formatted properly, this is my first post. I looked to see if this issue has been found before and I cannot find anyone who has had the same problem I am having.
I am trying to learn Java and cannot for the life of me figure out why my for loops are not outputting the last iteration. I am going through codeabbey's exercises and completed the first two relatively easily. However on the third and fourth problems, I cant get my for loop to output during the last iteration.
I began looking on google and thought I would compare my answer to someone else's. I couldn't see why mine wouldn't work when my code was almost identical to the person I found. So I copied their code and to my surprise I had the same problem when this code also would not output on the last iteration.
So, here is the context.
The website gives you a single number first which is the number of sets of the following numbers. For the third problem, you are to add the sets of two, output the sum followed by a space and loop through the entire batch. For the fourth problem, it is similar where the first number is the number of sets in the batch but you are to compare the two numbers and output the lower number. I will copy my code here for the third problem because the code is simpler.
Here is the code:
import java.util.Scanner;
public class Summation {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
for(int i = 0; i < n;i++){
int a = in.nextInt();
int b = in.nextInt();
System.out.println(a + b + " ");
}
}
}
Here is the input you are to copy and paste:
3
100 8
15 245
1945 54
and this is my output:
108 260
So, as you can see we are missing the last output here. I tried changing the for loop to (i < (n+1) ) which still didn't change anything. Any help would be GREATLY appreciated!
Ok so I tested it, and with your numbers, typing them in one by one it works. Copy pasting them, press enter one more time at the end of the copy. If you don't press enter, the scanner thinks you're still adding to the second number so it won't continue until enter is pressed.
I would try using println() as someone else suggested, or calling flush() at the end of the program to make sure something isn't being held in a buffer and not being written.

How to prevent value from changing automatically in java

I'm very new to Java and stackoverflow so I'm sorry if I seem ignorant but I wrote this program to multiply two numbers together using the Russian Peasant multiplication algorithm. The complete program includes far more operations and is hundreds of lines of code but I only included what I thought was necessary for this particular method. I have a test harness so I know that all the submethods work correctly. The problem that I'm struggling with though is the 3rd line where I'm adding factor1 to the product. The values add correctly but then when factor1 is multiplied by 2 in the 5th line then the value that was added to product in the 3rd line also gets doubled resulting in an incorrect product value. How can I make sure that when factor 1 is doubled that it doesn't carry backwards to the product term?
while (Long.parseLong(factor2.toString()) >= 1) {
if (factor2.bigIntArray[0] % 2 == 1) {
product = product.add(factor1);
}
factor1 = factor1.multiplyByTwo();
factor2 = factor2.divideByTwo();
}
I think in your method multiplyByTwo you use code
`datamember=datamember*2;`
rather than that try doing this
return new FactorClass(datamember*2);
so it doesnt change the added value.
it would be better if u could show the mulTiplyByTwo method code since that is where your actually are getting the changed value.

ArrayIndexOutOfBounds Exception When Using MillerUpdatingRegression Class

We've tried using the MillerUpdatingRegression class in one of our projects and ran into an issue. After creating an instance of the class, providing the number of variables to expect and adding observations from the entire sample set, we call the "regress(int[])" method, informing the regression process which variables we'd like to include (a subset of the entire predictor set).
When we do this, we receive an ArrayIndexOutOfBounds exception during the process because the number of variables to expect (nvars, provided when the MillerUpdatingRegression class was instantiated) is less than the number of variables passed to the "regress(int[])" method. Our understanding was that this array of integers could be a subset of the predictor indices from all observations.
Does anyone know what we're missing here?
==== Updated with Code ====
double predictorData[][] = new double[n][125];
double predictions[] = new double[n];
//predictorData is a [n x 125] two-dimensional array of
//features/predictors with n samples and 125 predictors
//predictionsArray is a n-length array of predictions
//for the sample set
int numberOfPredictorVariables = 125;
boolean includeConstantWhenBuildingModel = true;
MillerUpdatingRegression regression = new MillerUpdatingRegression(numberOfPredictorVariables,includeConstantWhenBuildingModel);
regression.addObservations(predictorData,predictionsArray)
int predictorsToIncludeInRegression[] = {0,3,9,11};
regression.regress(predictorsToIncludeInRegression);
//this is where the ArrayIndexOutOfBounds exception is generated
I can just guess here without a complete code example, but the number of observations must must be larger than the number of variables (which is 125 in your example).
To be more precisely, the n in your code must be larger than 125 for for the regression to work. The number of predictors passed into the regress method can be less than that.

Categories

Resources