BlueBoy Space

CPE49 Writeup

chevron_left 回上頁

2024-10-05

00100 - The 3n + 1 problem

題目連結

English - UVa Online Judge
中文 - ZeroJudge 高中生程式解題系統

參考解答

C
Java
Python

#include <stdio.h>
int tripleNPlusOne(int n){
    int count = 1;
    while(n!=1){
        if(n%2==0) n/=2;
        else n=n*3+1;
    	count++;
    }
    return count;
}
void main(){
    int i,j,temp_i,temp_j,max;
    while(scanf("%d %d",&i,&j) != EOF){
        max=0;
        temp_i = i>j ? j : i;
        temp_j = i>j ? i : j;
        for(int k=temp_i;k<=temp_j;k++){
            int count = tripleNPlusOne(k);
            if(count>max) max=count;
        }
        printf("%d %d %d\n",i,j,max);
    }
    return;
}
                

import java.util.*;
public class UVa100 {
    public static Scanner input = new Scanner(System.in);
    public static int tripleNPlusOne(int n) {
        int count = 1;
        while (n != 1) {
            if (n % 2 == 0) {
                n = n / 2;
            } else {
                n = n * 3 + 1;
            }
            count++;
        }
        return count;
    }
    public static void main(String[] args) {
        while (input.hasNextInt()) {
            int i = input.nextInt();
            int j = input.nextInt();
            int max = 0;
            int tempI = i>j ? j : i;
            int tempJ = i>j ? i : j;
            for(int k = tempI; k <= tempJ; k++) {
                int count = tripleNPlusOne(k);
                if (count > max) {
                    max = count;
                }
            }
            System.out.println(i + " " + j + " " + max);
        }
        input.close();
    }
}
                

def TripleNPlusOne(n):
    count=1
    while n!=1:
        if n%2:
            n=n*3+1
        else:
            n//=2
        count+=1
    return count
while True:
    try:
        i,j=map(int,input().split())
        max_count=0
        temp_i, temp_j = (i,j) if i < j else (j,i)
        for k in range(temp_i,temp_j+1):
            count=TripleNPlusOne(k)
            if count > max_count:
                max_count=count
        print(f'{i} {j} {max_count}')
    except EOFError:
        break