java - Method using recursion causing code to fail at run time, involves global variable -
this question poorly worded, how make code run desired without getting hundred error messages @ run time when use recursion? faulty program
public class collatz { public static int count; public static int pluscount() { return count++; } public static void collatz (int n) { if (n < count) { system.out.print(n + ""); } if (n == 1) return; if (n % 2 == 0) { pluscount(); collatz(n / 2); } else { pluscount(); collatz(3*n + 1); } } public static void main(string[] args) { int n = integer.parseint(args[0]); int[] array = new int [n+1]; (int = 0; <= n; i++) { count = 0; collatz(i); array [i] = count; } int max = stdstats.max(array); system.out.println(max); } }
if change collatz() method
public static void collatz (int n) { count ++; stdout.print(n + ""); if (n == 1 || n == 0) return; if (n % 2 == 0) collatz(n / 2); else collatz(3*n + 1); }
and remove pluscount() code, , input 7 argument, code runs , prints 01213105168421421516842163105168421722113417522613402010516842117 175226134020105168421
, it's supposed print 7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
here instructions java textbook if doesn't understand i'm trying accomplish:
consider following recursive function, related famous unsolved problem in number theory, known collatz problem or 3n + 1 problem.
public static void collatz(int n) { system.out.print(n + " "); if (n == 1) return; if (n % 2 == 0) collatz(n / 2); else collatz(3*n + 1); }
for example, call collatz(7)
prints sequence
7 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
as consequence of 17 recursive calls. write program takes command-line argument n , returns value of n < n number of recursive calls collatz(n)
maximized.
there 2 problem code
1.for loop in main method starts 0 causes problem.start iterating 1
(int = 1; <= n; i++)
2.no need put if (n < count)
in collatz method
Comments
Post a Comment