java - Any idea on how can I count the number of elements that verify an "if" condition? -
private static int chain(int n){ int count = 0; while(n > 1){ if(n % 2 == 0){ count++; //the value not stored return chain(n/2); } count++; //same thing return chain(3*n+1); } return count; //prints initial value (0) } }
i need print number of times chain method reoccurs.
remove count
variable method, , make static member of class. , prevent repeating yourlsef (dry principle), should increment count
variable @ top of method.
private static int count = 0; private static int chain(int n) { count++; while(n > 1) { if(n % 2 == 0) { return chain(n/2); } return chain(3*n+1); } return count; }
Comments
Post a Comment