1. 程式人生 > >PAT——1001 害死人不償命的(3n+1)猜想 (15)

PAT——1001 害死人不償命的(3n+1)猜想 (15)

scanner spa ati pat 測試用例 輸出 clas 格式 imp

對給定的任一不超過1000的正整數n,簡單地數一下,需要多少步(砍幾下)才能得到n=1?

輸入格式:每個測試輸入包含1個測試用例,即給出自然數n的值。

輸出格式:輸出從n計算到1需要的步數。

輸入樣例:

3

輸出樣例:

5
import java.util.Scanner;

  public class Main{
    public static void main(String[] args){

      int i = 0;
      Scanner s = new Scanner(System.in);
      int a = Integer.parseInt(s.nextLine());
      
if(a > 1000) System.out.println("please entery smaller than 1000"); else{ while(a > 1){ if(a%2 == 0){ a = a/2; i++; } else{ a = 3*a+1; a = a/2; i++; } } } System.out.println(i); } }

開始練習PAT的習題,開始從乙級開始訓練,註意練習時的規範,開始手動寫代碼,盡量不借助編譯器。

使用java語言必須註意幾個規範的地方:

(1) 類名必須為Main

(2)只在要求的輸出結果上面用System.out.println()

PAT——1001 害死人不償命的(3n+1)猜想 (15)