---
title: "3n+1"
author: "vcdemon"
date: "2014-06-13T00:03:26Z"
tags: []
categories: ["编程语言"]
slug: "3n-1"
draft: false
lastmod: "2014-06-13T00:03:26Z"
id: 2079010
url: "https://tbk.iteye.com/blog/2079010"
---

题目详情

对任何一个自然数n，如果它是偶数，那么把它砍掉一半；如果它是奇数，那么把(3n+1)砍掉一半。这样一直反复砍下去，最后一定在某一步得到n=1。卡拉兹在1950年的世界数学家大会上公布了这个猜想，传说当时耶鲁大学师生齐动员，拼命想证明这个貌似很傻很天真的命题，结果闹得学生们无心学业，一心只证(3n+1)，以至于有人说这是一个阴谋，卡拉兹是在蓄意延缓美国数学界教学与科研的进展……

我们今天的题目不是证明卡拉兹猜想，而是对给定的任一不超过1000的正整数n，简单地数一下，需要多少步（砍几下）才能得到n=1？

输入格式：

多组数据，每行一个整数0&lt;n&lt;=100000

输出格式：

每行一个数，表示结果。

 

 

答题说明

输入样例

1

3

输出样例：

0

5

 

 

```
import java.util.Scanner;

public class TestThree {
    public static int Test(int n) {
        int count=0;
        if (n==1) {
            return count;
        }
        
        if (n%2==0) {
            count++;
            count=count+Test(n/2);
        }else {
            count++;
            count=Test((3*n+1)/2)+count;
        }
        return count;
    }
    
    public static void main(String[] args) {
        Scanner scanner=new Scanner(System.in);
        while (true) {
            int n=scanner.nextInt();
            System.out.println(Test(n));
        }
    }
}
```