Day 0x11 UVa100 The 3n + 1 problem

题意

  • 输入两整数,根据演算法输出最大的 cycle length
  • 需要注意的有:
    1. 演算法
      1. input n
      2. print n
      3. if n = 1 then STOP
      4.     if n is odd then n ← 3n + 1
      5.     else n ← n/2
      6. GOTO 2
      
    2. cycle length
      • 根据演算法,纪录共跑几次回圈使得 n == 1

解法

  • 按照题目要求,先用 while 读入两整数,并用 if 让 i ≦ j,再把虚拟码转成 C 就行,如果有遇到更大值就更新
  • C code
    #include<stdio.h>
    
    void compare(int *a, int *b){
    
        int temp;
    
        if(*a > *b){
            temp = *a;
            *a = *b;
            *b = temp;
        }
    }
    
    int main(){
    
        int i, j;
        int n;
    
        while(scanf("%d %d", &i, &j) != EOF){
    
            printf("%d %d ", i, j);
    
            compare(&i, &j);            //let i < j
    
            int max = 0;
    
            while(i <= j){
    
                int count = 1;
                n = i;
    
                while(n != 1){
                    if(n % 2 == 1){     //odd
                        n = 3 * n + 1;  
                    }                   
                    else{               //even
                        n = n / 2;
                    }
                    count++;            //count the length
                }
    
                i++;
    
                if(count > max){
                    max = count;        //update max length
                }
            }
    
            printf("%d\n", max);
        }
    
        return 0;
    }
    

<<:  矛盾睡眠的断面

>>:  C#入门之ping

Day1 工业控制系统与普渡模型

工业控制系统 Industrial Control System 简称 ICS = 电脑与工业设备...

Day22_控制项(A17营运持续管理之资讯安全层面)-2021/10/05

▉A.17 Information Security Aspects Of Business营运持续...

DAY18-JAVA的抽象类别(1)

透过继承,我们可以从原有的类别衍生出新的类别,原有的类别称为父类别,而衍生出的类别称为子类别。透过这...

18. 订OKRs新手常见错误

前言 这篇跟工程师其实没那麽有关,适合给新手leader定OKRs的时候看看。 演讲总结 今天要讲...

Day 3 Ruby 基础运算子

写在前面 刚开始学程序语言的时候总会有一些看起来很简单但很容易跳进去的坑,基础运算子还有逻辑运算在我...