for reason, having trouble loop in first method of code, ans. if @ while , while loops, while loop working fine, running through each element in linkedhashset, though do-while stops after while has had first run through. num1 doesn't move passed 12, while num2 becomes every value in set, , not sure why. figured out printing num1 , num2, , unable figure out why happening. , appreciated. here 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 values set do{//loop values set num1=itr.next();//assigns each object in set num while (itr.hasnext()){//loop values set add num2=itr.next();//assigns each object in set 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 loop counter int total=0;//total of numbers 0-28123 int fin;//final answer boolean abundant; set<integer> abund=new linkedhashset<integer>(); (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
you need build sums of pairs set of abundant numbers a, ai <= aj. cannot execute nested loop using single iterator, which, definition, goes first last. it's difficult use 2 iterators or foreach loops, since inner loop must skip position outer loop holds. therefore...
use list hold abundant numbers iteration:
public static int ans(list<integer> abund, int total){ for( int = 0; < 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 list enough, since numbers different anyway.
Comments
Post a Comment