3n+1問題


每周一題之1  3n+1問題

 大水題

PC/UVa IDs: 110101/100

Popularity: A

Success rate: low Level: 1

測試地址:

https://vjudge.net/problem/UVA-100

 

[問題描述]

 

考慮如下的序列生成算法:從整數 n 開始,如果 n 是偶數,把它除以 2;如果 n 是奇數,把它乘 3 加1。用新得到的值重復上述步驟,直到 n = 1 時停止。例如,n = 22 時該算法生成的序列是:

22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1

 

人們猜想(沒有得到證明)對於任意整數 n,該算法總能終止於 n = 1。這個猜想對於至少 1 000 000內的整數都是正確的。

 

對於給定的 n,該序列的元素(包括 1)個數被稱為 n 的循環節長度。在上述例子中,22 的循環節長度為 16。輸入兩個數 i 和 j,你的任務是計算 i 到 j(包含 i 和 j)之間的整數中,循環節長度的最大值。

 

[輸入]

輸入每行包含兩個整數 i 和 j。所有整數大於 0,小於 1 000 000。

 

[輸出]

對於每對整數 i 和 j,按原來的順序輸出 i 和 j,然后輸出二者之間的整數中的最大循環節長度。這三個整數應該用單個空格隔開,且在同一行輸出。對於讀入的每一組數據,在輸出中應位於單獨的一行。

 

[樣例輸入]

1 10

100 200

201 210

900 1000

 

[樣例輸出]

1 10 20

100 200 125

201 210 89

900 1000 174

 

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int i,j;
        while (in.hasNext()) {
            i = in.nextInt();
            j = in.nextInt();
       int a=i,b=j;
if (i > j) { int k = i; i = j; j = k; } int temp = Integer.MIN_VALUE; for (int n = i; n <= j; n++) { int x = fun(n); temp=Math.max(x, temp); } System.out.println(a+ " " + b+ " " + temp); } } static int fun(int n) { int count = 0; while (n != 1) { if (n % 2 == 0) n = n / 2; else n = 3 * n + 1; count++; } count++; return count; } }

優化解法: 

 

package december.year18;

import java.util.HashMap;
import java.util.Scanner;

/**
 *  3n+1
 * @author DGW-PC
 * @data   2018年12月9日
 */
public class Solution1 {
    
     static HashMap<Integer, Integer> map=new HashMap<>();
        public static void main(String[] args) {
            Scanner cin=new Scanner(System.in);
            while(cin.hasNext()) {
                int i=cin.nextInt();
                int j=cin.nextInt();
                int a=i;
                int b=j;
                if(i>j) {
                    a=a^b;
                    b=a^b;
                    a=a^b;
                }
                int maxn=Integer.MIN_VALUE;
                for (int k =i; k <= j; k++) {
                    //檢查后面大區間的重復計算問題
                    Integer fi = map.get(k);
                     if(fi==null) {
                         fi=f(k);
                         map.put(k, fi);
                     }
                     maxn=Integer.max(maxn, fi);
                }
                System.out.println(i+" "+j+" "+maxn);
            }
        }

        private static Integer f(long fi) {
            int count=1;
            while(fi!=1) {
                if((fi&1)==0) {
                    fi/=2;     
                }else {
                    fi=fi*3+1;
                }
                count++;
            }
            return count;
        }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM