为啥TLE,5TLE1AC.

B2077 角谷猜想

nodejs @ 2023-08-21 22:27:43

#include<bits/stdc++.h>
using namespace std;
int main(){
    long long n;
    scanf("%lld",&n);
    while(1){
        if(n==1){
            cout<<"End";
            return 0;
        }
        if(!n%2){
            cout<<n<<"/2="<<n/2<<endl;
            n=n/2;
        }
        else{
            cout<<n<<"*3+1="<<n*3+1<<endl;
            n=n*3+1;
        }
    }
    return 0;
}

为啥TLE,5TLE1AC.


by Elairin176 @ 2023-08-21 22:35:47

@nodejs 11 行应该改为:

if(!(n%2)){

注意非运算的优先级高于模。


by heyx0201 @ 2023-08-21 22:47:12

@nodejs 把endl改成\n吧,不然很容易TLE


by yuanshenhutao666 @ 2023-10-02 07:44:27

#include <iostream>
using namespace std;
void collatzConjecture(long long num) {
    while (num != 1) {
        std::cout << num;
        if (num % 2 == 0) {
            // 如果是偶数,则除以2
            num /= 2;
            std::cout << "/2=" << num << std::endl;
        } else {
            // 如果是奇数,则乘以3再加1
            num = num * 3 + 1;
            std::cout << "*3+1=" << num << std::endl;
        }
    }
    std::cout << "End" << std::endl;
}
int main() {
    long long num;
    std::cin >> num;
    collatzConjecture(num);
    return 0;
}

by lizhuohang2013 @ 2023-10-17 22:32:29

@nodejs 把if(!n%2) 改成 if(n%2!=0)就可以了


|