---
title: "3x+1问题"
author: "抛出异常的爱"
date: "2010-08-05T09:28:25Z"
tags: []
categories: ["非技术"]
slug: "3x-1"
draft: false
lastmod: "2010-08-05T11:00:08Z"
id: 729436
url: "https://loveexception.iteye.com/blog/729436"
---

今天看到一个题在入门版.....
http://www.iteye.com/topic/728160
挪过来看看.


> **Crusader** writes:
> 
> 3x+1问题，它描述的是这样一个现象：
> 任取一个自然数，如果它是偶数，就把它除以2，如果它是奇数，就把它乘3再加上1。如此，就得到了一个新的自然数。再按照上述规则反复操作新产生的自然数，我们就会得到一串自然数，而最终得到的自然数序列将陷在4→2→1这个循环中。。。
> 
> 如 5→16→8→4→2→1→4→2→1。。。
>      7→22→11→34→17→52→26→13→40→20→10→5→16→8→4→2→1→4→2→1。。。
> 
> 这个猜想目前还无法证明，只能穷举，最闲的人已经验证到100*2的50次方。。。
> 
> 运行的时候，循环改小点，否则估计要运行1千万年左右，应该都活不到那么长吧...
> [code=java]
> public class _3X1 {
> 		
> 	// 是否奇数
> 	private static boolean isOdd(long i){
> 		return (i&1L)==1L;
> 	}
> 	
> 	// 判断是否4 | 2 | 1
> 	private static boolean is_4_2_1(long i){
> 		return i==4 || i==2 || i==1;
> 	}
> 	
> 	// 判断是否2的次方,如果是,直接断定满足3x+1
> 	private static boolean isPower2(long i){
> 		int count = 0;
> 		while(i>0 && count<2){
> 			i = i & (i-1L);
> 			count++;
> 		}
> 		return count==1;
> 	}
> 	
> 	// 满足3x+1猜想则返回true,否则死循环
> 	public static boolean _3x1(long i){
> 			int flag = 0;
> 			while(flag<3){
> 				// 如果是奇数
> 				if(isOdd(i)){
> 					i = i*3L+1L;				
> 				// 如果是偶数
> 				}else{
> 					i >>= 1;		
> 				}
> 				
> 				if(is_4_2_1(i)){
> 					flag++;
> 				}else{
> 					flag=0;
> 				}
> 			}
> 
> 		return true;
> 	}
> 	
> 	public static void main(String[] args) {
> 
> 		for(long i=1; i<Long.MAX_VALUE; i++){
> 
> 			if(isPower2(i) || _3x1(i)){
> 				System.out.println(i);
> 			}
> 
> 		}
> 
> 	}
> 
> }
> [/code]