傳送門
https://pintia.cn/problem-sets/994805260223102976/problems/994805325918486528
題目
卡拉茲(Callatz)猜想:
對任何一個(gè)自然數(shù)n太抓,如果它是偶數(shù),那么把它砍掉一半扳肛;如果它是奇數(shù)叔汁,那么把(3n+1)砍掉一半统求。這樣一直反復(fù)砍下去检碗,最后一定在某一步得到n=1÷肓冢卡拉茲在1950年的世界數(shù)學(xué)家大會上公布了這個(gè)猜想折剃,傳說當(dāng)時(shí)耶魯大學(xué)師生齊動員,拼命想證明這個(gè)貌似很傻很天真的命題像屋,結(jié)果鬧得學(xué)生們無心學(xué)業(yè)怕犁,一心只證(3n+1),以至于有人說這是一個(gè)陰謀己莺,卡拉茲是在蓄意延緩美國數(shù)學(xué)界教學(xué)與科研的進(jìn)展……
我們今天的題目不是證明卡拉茲猜想奏甫,而是對給定的任一不超過1000的正整數(shù)n,簡單地?cái)?shù)一下篇恒,需要多少步(砍幾下)才能得到n=1扶檐?
輸入格式:每個(gè)測試輸入包含1個(gè)測試用例凶杖,即給出自然數(shù)n的值胁艰。
輸出格式:輸出從n計(jì)算到1需要的步數(shù)。
輸入樣例:
3
輸出樣例:
5
分析
這道題需要用while循環(huán)對n進(jìn)行判斷智蝠,每次n按照題目要求進(jìn)行運(yùn)算腾么,每運(yùn)算一次,給計(jì)數(shù)器變量自增1杈湾,直到n為1時(shí)解虱,停止循環(huán),輸出計(jì)數(shù)器變量即可漆撞。
源代碼
//C/C++實(shí)現(xiàn)
#include <stdio.h>
#include <iostream>
using namespace std;
int main(){
int n;
scanf("%d", &n);
int count = 0;
while(n != 1){
if(n % 2 != 0){
n = (3 * n + 1) / 2;
count ++;
}
else{
n /= 2;
count ++;
}
}
printf("%d\n", count);
return 0;
}
//Java實(shí)現(xiàn)
import java.util.Scanner;
public class Main {
public static void main(String []args){
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int count = 0;
if(n > 0 && n<=1000) {
while (n != 1) {
if (n % 2 == 0) {
count++;
n = n / 2;
} else {
count++;
n = (3 * n + 1) / 2;
}
}
}
System.out.println(count);
}
}