PAT-BASIC1001——害死人不偿命的(3n+1)猜想
我的PAT-BASIC代码仓:https://github.com/617076674/PAT-BASIC
原题链接:https://pintia.cn/problem-sets/994805260223102976/problems/994805325918486528
题目描述:
知识点:迭代
思路:迭代求解步数
本题就是一个简单的迭代累加计数问题。
时间复杂度不好计算,跟具体输入的测试用例的数据有关。空间复杂度是O(1)。
C++代码:
#include<iostream>
using namespace std;
int main() {
int n;
cin >> n;
int count = 0;
while (n > 1) {
count++;
if (n % 2 == 0) {
n /= 2;
} else {
n = (3 * n + 1) / 2;
}
}
cout << count << endl;
return 0;
}
C++解题报告:
JAVA代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
int count = 0;
while(num != 1){
if(num % 2 == 0){
num /= 2;
}else{
num = (3 * num + 1) / 2;
}
count++;
}
System.out.println(count);
}
}
JAVA解题报告: