java - TLE for WILLITST (SPOJ) -
i've written code in java below question, , getting correct answer on machine. when submit on spoj, giving tle (time limit exceeded) error. can please me in correcting / improvising this?
[question]: http://www.spoj.com/problems/willitst/
here code tried:
import java.io.bufferedreader; import java.io.inputstreamreader; import java.math.biginteger; import java.util.arraylist; class willitst { public static void main(string[] args) throws exception { bufferedreader br=new bufferedreader(new inputstreamreader(system.in)); biginteger n=biginteger.valueof(long.parselong(br.readline())); arraylist<biginteger> al=new arraylist<biginteger>(); biginteger x=biginteger.valueof(2); biginteger y=biginteger.valueof(3); while(n.compareto(biginteger.one)==1){ al.add(n); if(n.mod(x) == biginteger.zero) n=n.divide(x); else n=y.multiply(n).add(y); if(al.contains(n)) { system.out.println("nie"); return; } } system.out.println("tak"); } }
thanks in advance.
submitted below code successfully, w/o tle:
import java.io.bufferedreader; import java.io.inputstreamreader; import java.math.biginteger; import java.util.hashset; import java.util.set; class willitst_biginteger { public static void main(string[] args) throws exception { bufferedreader br=new bufferedreader(new inputstreamreader(system.in)); biginteger n=biginteger.valueof(long.parselong(br.readline())); set<biginteger> s=new hashset<biginteger>(); biginteger x=biginteger.valueof(2); biginteger y=biginteger.valueof(3); while(n.compareto(biginteger.one)==1){ if(!s.add(n)){ system.out.println("nie"); return; } if((n.and(n.subtract(biginteger.one))).equals(biginteger.zero)){ system.out.println("tak"); return; } if((n.and(biginteger.one)).equals(biginteger.zero)) n=n.divide(x); else n=y.multiply(n).add(y); } system.out.println("tak"); } }
Comments
Post a Comment