Tuesday 15 January 2013

java - UVa's 3n+1 - why does my code exceed time limit? -



java - UVa's 3n+1 - why does my code exceed time limit? -

the question explained below.

consider next algorithm:

1. input n 2. if n = 1 stop 3. if n odd n = 3n+1 4. else n=n/2 5. goto 2

given input 22, next sequence of numbers printed :

22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1

it conjectured algorithm above terminate (when 1 printed) integral input value. despite simplicity of algorithm, unknown whether conjecture true. has been verified, however, integers n such 0 < n < 1,000,000 (and, in fact, many more numbers this.) given input n, possible determine number of numbers printed (including 1). given n called cycle-length of n. in illustration above, cycle length of 22 16. 2 numbers i , j determine maximum cycle length on numbers between i , j.

sample input: 1 10 sample output: 1 10 20

here solution.

import java.io.ioexception; public class main{ public static void main(string[]args) { new n1().run(); } public static string readline(int maxlength) { byte[] bytes = new byte[maxlength]; int length=0; int input = 0; while(length<maxlength) { seek { input = system.in.read(); } grab (ioexception e) { homecoming null; } if(input=='\n') break; bytes[length] += input; length++; } if(length==0) homecoming null; homecoming new string(bytes, 0, length); } } class n1 implements runnable { @override public void run() { string line = main.readline(100); while(line!=null) { solve(line); line = main.readline(100); } } private void solve(string input) { string[] tokens = input.trim().split("\\s+"); if(tokens.length!=2) return; int i=-1, j=-1; try{ = integer.parseint(tokens[0]); j = integer.parseint(tokens[1]); }catch(exception e) { return; } if(i<=0||j<=0) return; int low, high; low = (i<j) ? :j; high = i+j-low; int max = -1; for(int k=i;k<=j;k++) { max = math.max(max, cyclelength(k)); } system.out.println(i+" "+j+" "+max); return; } private int cyclelength(int k) { int length = 1; long n = k; while(n!=1) { n = (n & 1)==0 ? n>>1 : n*3+1; length++; } homecoming length; } }

above solution uva 3n+1 question. have no problem working code on laptop , responds quikly. however, verdict 'time limit exceeded' what's problem?

your run() method infinite loop calls readline() , readline() not check end of file or end of input. programme trying read line when end of file or end of input reached. waits forever , time runs out.

java

No comments:

Post a Comment