uva 100 The 3n + 1 problem

題目  根據給定的運算規定,算循環數字個數。輸入一個範圍,返回範圍內所有數中循環數最大的

注意  輸入的範圍不一定就是第一個比第二個小,要注意判斷

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

#include<sstream>

#include<cstdio>

#include<iostream>

#include<math.h>

#include <map>

#include <vector>

#include <algorithm>

using namespace std;

int func(int n){

    int i = 1;

    while(1) {

        if(n == 1) break;

        if(n % 2 == 1) {

            i++;

            n = 3 * n + 1;

        }

        if(n % 2 == 0) {

            i++;

            n /= 2;

        }

    }

    return i;

}

int main(){

    int a,b;

    vector<int> num;

    while(cin>> a >> b) {

        int flag = 1;

        if(a > b){

            int temp = a;

            a = b;

            b = temp;

            flag=0;

        }

        for(int i = a; i <= b; i ++) {

            num.push_back(func(i)); //1️⃣func函數的嵌套

        }

    

    sort(num.begin(), num.end());//2️⃣sort函數兩個迭代器組成,增序排列

    if(flag == 1)printf("%d %d %d\n",a,b,num[num.size()-1]);//3️⃣size()-1纔是最後一個

        else printf("%d %d %d\n",b,a,num[num.size()-1]);//4️⃣注意輸出還是原順序a,b

    num.clear();

    }

    

    

    

    return 0;

}

/*

 1 10

 100 200

 201 210

 900 1000

 */



發佈了50 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章