UVaOJ 100 - The 3n + 1 problem

来源:互联网 发布:淘宝店铺怎么管理 编辑:程序博客网 时间:2024/05/29 13:04

著名的3n+1。2012年2月份在Programming Challenge官网上写的。当时学了2天JAVA,还是用的PC上的输入模板。PC现在已经关闭了。

10050241100The 3n + 1 problemAcceptedJAVA0.1842012-04-29 01:09:49

import java.io.*;class Main implements Runnable{static String ReadLn(int maxLength){  // utility function to read from stdin,// Provided by Programming-challenges, edit for style onlybyte line[] = new byte [maxLength];int length = 0;int input = -1;try{while (length < maxLength){//Read untill maxlengthinput = System.in.read();if ((input < 0) || (input == '\n')) break; //or untill end of line ninputline [length++] += input;}if ((input < 0) && (length == 0)) return null;  // eofreturn new String(line, 0, length);}catch (IOException e){return null;}}public static void main(String args[])  // entry point from OS{Main myWork = new Main();  // Construct the bootloadermyWork.run();            // execute}public void run() {new myStuff().run();}}class myStuff implements Runnable{public void run(){String input;while ((input = Main.ReadLn(128)) != null) {String[] tokens = input.trim().split("\\s+");int sn = new Integer(tokens[0]).intValue();int en = new Integer(tokens[1]).intValue();doline(sn,en);}}public static int rx (int n){int rev = 0;if (n % 2 == 0){rev = n/2;}if (n % 2 == 1){rev = 3*n+1;}return rev;}public static void doline(int sn,int en){int info[];int startv = (sn <= en? sn : en);int endv = (sn == startv? en:sn);int length = endv - startv;info = new int[length+1];for (int i=startv;i<startv+length;i++){int times = 1; //starts with the number itselfint nx = i;while (nx != 1){times ++;nx = rx(nx);}info[i-startv]=times;}int max = info[0];for (int i=0;i<length+1;i++){if (info[i] > max){max = info[i];}}System.out.print(sn+" "+en+" "+max+"\n");}}


原创粉丝点击