There are two errors in the following JAVA program:
  static void g(int i){
   if(i==1){return;}
   if(i%2==0){g(i/2);return;}
   else {g(3*i);return;}
   }
  please correct them to make sure we can get the printed-out result as below:
  3 10 5 16 8 4 2 1感觉题目有点奇怪,大家说说怎么改

解决方案 »

  1.   

    public class Play4 {
    public static void main(String[] args) {
              g(3);
    } static void g(int i) {
    System.out.println(i);
    if (i == 1) {
    return;
    }
    if (i % 2 == 0) {
    g(i / 2);
    return;
    } else {
    g(3 * i+1);
    return;
    }
    }
    }
      

  2.   

    这道题目源于uva(一个acm试题站点acm.uva.es)的3*n+1 problem 
    该问题能够收敛是基于一个数学原理
      

  3.   

    static void g(int i) {
            System.out.print(i + " ");
            if (i == 1) {
                return;
            }
            if (i % 2 == 0) {
                g(i / 2);
                return;
            } else {
                g(3 * i + 1);
                return;
            }
        }
      

  4.   

    public class Play4 {
    public static void main(String[] args) 
            {
                 g(3);
    } static void g(int i) 
             {
    System.out.println(i);
    if (i == 1) 
                      {
    return;
    }
    if (i % 2 == 0) 
                      {
         g(i / 2);
         return;
    } else 
                      {
         g(3 * i+1);
         return;
    }
    }
    }