Reputation: 1691
for some reason, I am having trouble with the loop in the first method of my code, ans. if you look at the do while and while loops, the while loop is working fine, running through each element in the LinkedHashSet, though the do-while stops after the while has had its first run through. So num1 doesn't move passed 12, while num2 successfully becomes every value in the Set, and I am not sure why. I figured this out by printing num1 and num2, and I am unable to figure out why this is happening. Any and all help is appreciated. Here is my code:
import java.util.Set;
import java.util.LinkedHashSet;
import java.util.Iterator;
public class main{
public static int ans(Set<Integer> abund,int total){
int sum;
Object num1;
Object num2;
Iterator itr=abund.iterator();//creates iterator to get values from set
do{//loop to get all values from set
num1=itr.next();//assigns each object in set to a num
while (itr.hasNext()){//loop to get all values from set to add
num2=itr.next();//assigns each object in set to a num
sum=((int) num1+(int) num2);
total-=sum;
}
}while (itr.hasNext());
return total;
}
public static boolean abun(int y){
int x;
int facsum=0;
for(x=1;x<y;x++){
if (y%x==0){
facsum+=x;
}
}
if (facsum>y){
return true;
}
else{
return false;
}
}
public static void main(String[] args){
int x;//for loop counter
int y;//another for loop counter
int total=0;//total of all numbers from 0-28123
int fin;//final answer
boolean abundant;
Set<Integer> abund=new LinkedHashSet<Integer>();
for (x=0;x<28124;x++){
abundant=abun(x);
if (abundant==true){
abund.add(x);
}
total+=x;
}
fin=ans(abund,total);
System.out.println("Final: "+fin);
}
}
Thanks
Upvotes: 0
Views: 60
Reputation: 31290
You need to build all sums of pairs from the set of abundant numbers A, where ai <= aj. You cannot execute this nested loop using a single iterator, which, by definition, goes from first to last. It's also somewhat difficult to use two iterators or foreach loops, since the inner loop must then skip to the position where the outer loop holds. Therefore...
Use a List to hold the abundant numbers for this iteration:
public static int ans(List<Integer> abund, int total){
for( int i = 0; i < abund.size(); ++i ){
for( int j = i; j < abund.size(); ++j ){
total -= abund.get(i) + abund.get(j);
}
}
return total;
}
Set<Integer> abund=new HashSet<Integer>(); // List-ArrayList
fin = ans( new ArrayList( abund ), total );
Actually, using just a List is good enough, since numbers are different anyway.
Upvotes: 1
Reputation: 122
Iterator is a pointer to a set. And you assign only one. Code will exit from outer loop imediately after inner loop is done. If you need to iterate twice in the field. You will need two iterators. But i will suggest to convert set to array (Integer[] ab = abund.toArray().
And use for loops.
Upvotes: 1