Before we begin let me say that I already found the solution to the problem, but I am still unable to explain why it solved the problem, so I am here to ask you experts why this java code produces the results I indeed see.
The two pairs of code I am going to show are meant to find all the prime factors of a number (it is not my original code, I took it from Project Euler, and I'm further using it solve a later, harder problem in the project, but that is not relevant).
I am going to post the first code and its corresponding incorrect result, then show the second code, its correct result, and I will lastly point out the only line that is different between the two.
The question I have for you guys, because I can't answer it, is why is the first result coming up this way? Why does the solution of changing that single line of code work?
The only explanation I can give is that for some reason if you initiate an ArrayList by saying ArrayList something = oldArrayList they are both pointing to the same ArrayList... I'm not satisfied with this answer because it doesn't make sense with the java structure I thought I knew.
So here we go:
First Code: -
public static void main(String[] args) {
-
utils.print(allPrimeFactorsAndTheirPowers(10));
-
}
-
-
public static HashMap<Integer, Integer> allPrimeFactorsAndTheirPowers(int input) {
-
ArrayList<Integer> primeFactors = new ArrayList<Integer>((int)Math.sqrt((double)input));
-
ArrayList<Integer> powers = primeFactors;
-
HashMap<Integer, Integer> factorsAndPowers = new HashMap<Integer,Integer>((int)Math.sqrt((double)input));
-
int currentPower = 0;
-
-
if (!isPrime(input)) {
-
int n = input;
-
-
if(n % 2 == 0) {
-
currentPower++;
-
primeFactors.add(Integer.valueOf(2));
-
n = n / 2;
-
while(n % 2 == 0) {
-
currentPower++;
-
n = n / 2;
-
}
-
powers.add(Integer.valueOf(currentPower));
-
currentPower=0;
-
}
-
int factor = 3;
-
int maxFactor = (int)Math.sqrt((double) n);
-
while(n > 1 && factor <= maxFactor) {
-
if (n % factor == 0) {
-
currentPower++;
-
n = n / factor;
-
primeFactors.add(factor);
-
while(n % factor == 0) {
-
currentPower++;
-
n = n / factor;
-
}
-
maxFactor = (int)Math.sqrt((double)n);
-
powers.add(Integer.valueOf(currentPower));
-
currentPower=0;
-
}
-
factor = factor+2;
-
} if (n != 1) {
-
primeFactors.add(Integer.valueOf(n));
-
powers.add(Integer.valueOf(1));
-
}
-
} else {
-
primeFactors.add(Integer.valueOf(input));
-
powers.add(Integer.valueOf(1));
-
}
-
-
for(int i = 0; i < primeFactors.size(); i++) {
-
factorsAndPowers.put(primeFactors.get(i), powers.get(i));
-
}
-
-
return factorsAndPowers;
-
}
-
Incorrect Result:
5 : 5
1 : 1
2 : 2
Second Code: -
public static void main(String[] args) {
-
utils.print(allPrimeFactorsAndTheirPowers(10));
-
}
-
-
public static HashMap<Integer, Integer> allPrimeFactorsAndTheirPowers(int input) {
-
ArrayList<Integer> primeFactors = new ArrayList<Integer>((int)Math.sqrt((double)input));
-
ArrayList<Integer> powers = new ArrayList<Integer>((int)Math.sqrt((double)input));
-
HashMap<Integer, Integer> factorsAndPowers = new HashMap<Integer,Integer>((int)Math.sqrt((double)input));
-
int currentPower = 0;
-
-
if (!isPrime(input)) {
-
int n = input;
-
-
if(n % 2 == 0) {
-
currentPower++;
-
primeFactors.add(Integer.valueOf(2));
-
n = n / 2;
-
while(n % 2 == 0) {
-
currentPower++;
-
n = n / 2;
-
}
-
powers.add(Integer.valueOf(currentPower));
-
currentPower=0;
-
}
-
int factor = 3;
-
int maxFactor = (int)Math.sqrt((double) n);
-
while(n > 1 && factor <= maxFactor) {
-
if (n % factor == 0) {
-
currentPower++;
-
n = n / factor;
-
primeFactors.add(factor);
-
while(n % factor == 0) {
-
currentPower++;
-
n = n / factor;
-
}
-
maxFactor = (int)Math.sqrt((double)n);
-
powers.add(Integer.valueOf(currentPower));
-
currentPower=0;
-
}
-
factor = factor+2;
-
} if (n != 1) {
-
primeFactors.add(Integer.valueOf(n));
-
powers.add(Integer.valueOf(1));
-
}
-
} else {
-
primeFactors.add(Integer.valueOf(input));
-
powers.add(Integer.valueOf(1));
-
}
-
-
for(int i = 0; i < primeFactors.size(); i++) {
-
factorsAndPowers.put(primeFactors.get(i), powers.get(i));
-
}
-
-
return factorsAndPowers;
-
}
-
Correct Result:
5 : 1
2 : 1
The only line that changes:
Incorrect Line of Code: - ArrayList<Integer> powers = primeFactors;
Correct Line of Code: - ArrayList<Integer> powers = new ArrayList<Integer>((int)Math.sqrt((double)input));
Your help and knowledge is much appreciated,
-blazed
1 7526
I believe I found the answer:
"Array variables are references to a block of elements
When you declare an array variable, Java reserves only enough memory for a reference (Java's name for an address or pointer) to an array object. References typically require only 4 bytes. When an array object is created with new, a reference is returned, and that reference can then be assigned to a variable. When you assign one array variable to another, only the reference is copied. For example,
int[] a = new int[] {100, 99, 98}; // "a" references the array object.
int[] b; // "b" doesn't reference anything.
b = a; // Now "b" refers to the SAME array as "a"
b[1] = 0; // Also changes a[1] because a and b refer to the same array." - http://www.leepoint.net/notes-java/d...ys/arrays.html
I had no idea this was the case, but it explains another problem I was having with arrays this time, and it completely explains what happened above.
-blazed
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: lkrubner |
last post by:
I'm offering users the ability to type weblog posts into a form and
post them. They type the text into a TEXTAREA which is on a form. The
form, when submitted, hits a PHP script. Before it is submitted, while
they are typing, I'm trying to offer them some common word processing
functions.
I want to implement unlimited undo and redo for the textarea. I've set
the textarea to onChange="addToArrayOfPastWork()";
My undo button gives me...
|
by: nicver |
last post by:
I am fixing a client's Web site and for some reason an ASP class does
not want to use the variables it retrieves when it initialiases.
This is an excerpt of the class and it is enough to show what is not
working correctly:
------
Class clsAd
private pintMyData1
private pintMyData2
private pintMyData3
|
by: Rich |
last post by:
Dim bNcd, bNcm, bNqa, bNcur, bN0, bN1, bN2, bN3, bN4 As Boolean
Dim arrBool As Boolean() = {bNcd, bNcm, bNqa, bNcur, bN0, bN1, bN2, bN3, bN4}
Dim i As Integer
bNcd = True
bNcm = True
bNqa = True
bNcur = True
bN0 = True
bN1 = True
|
by: Niu Xiao |
last post by:
I saw a lot of codes like:
void foo(void* arg)
void bar(void** arg)
f((void*)p)
but what does void pointer mean in c? I just know it stands for generic
pointer.
thanks.
|
by: jagguy |
last post by:
this works
char *p ;
p="xat";
cout << p <<endl;
| |
by: archana |
last post by:
Hi all,
I want to develop one application for storing tasklist.
so what i am doing is i have one class which is containing arraylist
where i am storing details about task.
At a time of serializing this it is working properly. But i am not able
to deserialize back this data.
|
by: dashprasannajit |
last post by:
package djvusearching;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.lucene.analysis.cjk.CJKAnalyzer;
//import org.apache.lucene.analysis.standard.StandardAnalyz er;
import org.apache.lucene.queryParser.ParseException;
|
by: basm101 |
last post by:
Hello,
Firstly, apologies if this should be in the javascript forum - I wasnt sure which was most appropriate to post this question in...
I am not sure if my problem is caused by the way I am mixing java and javascript in my jsp and if it can be fixed.
If currentObservation.getComment() (java) is not null then all is well. But if it is null, instead of just setting document.commentForm.commentBox.value to a blank string I get a...
|
by: Andryanus |
last post by:
Hello everyone,
Does anyone have experience accessing Java Jar Object with ASP?
Please kindly advise.
Thank you.
|
by: geosmy |
last post by:
Hi everyone,
First post here!
I have been trying to upgrade to Acc2007 looking forward to using Split Forms.
To my horror I have just discovered that Split Forms do not hold variables at module level!!! Although code is working perfectly well when in Single Form view, when switching to Split Form view... problems. This must definitely be a bug unless there are limitations to Split Forms (doubt it).
Although there might be some...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
| |
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |