My code is getting a runtime error in UVA online judge, but it is running fine in my compiler.I don't know exactly where the problem is. So help me. Below is my code.
class reverseAdd {
public static int checkPalingdromMarker(long [] a1,long [] a2){
int c=0;
for(int q=0;q<a2.length/2;q++){
if(a1[q]!=a2[q]){
break;
}
else c++;
}
if(c==(a2.length/2))
{
return 1;
}
return 0;
}
public static void checkPalingdrom(long [] a1,long [] a2){
int c=0;
for(int q=0;q<a2.length/2;q++){
if(a1[q]!=a2[q]){
System.out.println("Not Palingdrom");
break;
}
else c++;
}
if(c==(a2.length/2))
{
System.out.println("Palingdrom found");
}
}
public static long [] reverseNumberDigits(long numToDigits){
String string = Long.toString(numToDigits);
long[] digits = new long[string.length()];
/*
for(int y = 0; y<string.length(); ++y){
digits[y] = Long.parseLong(string.substring(y, y+1));
}
*/
int reverse=0,i=string.length();
while( numToDigits != 0 )
{
reverse = reverse * 10;
digits[i-1] = reverse + numToDigits%10;
numToDigits = numToDigits/10;
i=i-1;
}
return digits;
}
public static long reverseNumber(long numberToReverse){
long reverse = 0;
while( numberToReverse != 0 )
{
reverse = reverse * 10;
reverse = reverse + numberToReverse%10;
numberToReverse = numberToReverse/10;
}
return reverse;
}
public static long [] readNumsFromCommandLine() {
Scanner s = new Scanner(System.in);
int count = s.nextInt();
s.nextLine(); // throw away the newline.
long [] numbers = new long[count];
for(int i = 0; i < count; i++){
if(s.hasNextLong()){
numbers[i] = s.nextLong();
s.nextLine();
}
}
return numbers;
}
public static void main(String[] args) {
long[] numbers = readNumsFromCommandLine();
int inputLength=numbers.length;
for(int f=0;f<inputLength;f++){
int countAddition=1;
long a=numbers[f]+reverseNumber(numbers[f]);
for(int x=0;x<1000;x++){
System.out.println(a);
if(checkPalingdromMarker(reverseNumberDigits(reverseNumber(a)), reverseNumberDigits(a))==0){
countAddition++;
a=a+reverseNumber(a);
}
else{
System.out.println(countAddition+" "+reverseNumber(a));
break;
}
}
}
}
}
UVa Online Judge has specific requirements for submitted code in order for it to correctly compile. There are 2 mistakes in your code preventing compilation.
Change the first line of your code:
class reverseAdd {
to
import java.util.*;
class Main {
Note: I ran your code and it will result in a "Wrong Answer" result in UVa.
For sample input:
3
24 1
4358 754
305 794
The expected output is:
34
1998
1
Your code's (incorrect) output is:
4358 754
305 794
66
1 66
12892
42713
74437
147884
636625
1163261
2786872
7 2786872
808
1 808
Related
I'm trying to create a program that asks for 10 integers and puts those numbers into an array of negative, positive, and odd arrays. In the end, I want the program to print out 3 rows of numbers that separate the users 10 numbers into "odd", "even", and negative". When I run this I get "error: 'void' type not allowed here"
import java.util.Scanner;
public class ArrayPractice{
private static void showArray(int[] nums)
{
for (int i=0; i<nums.length;i++)
{
if(nums[i]!=0)
{
System.out.println(nums[i] + " ");
}
}
}
public static void main(String[] args){
int evenArray[] = new int[10];
int evenCount = 0;
int oddArray[] = new int[10];
int oddCount = 0;
int negArray[] = new int[10];
int negCount = 0;
Scanner input = new Scanner(System.in);
for(int i = 0; i<10; i++)
{
System.out.println("Number? " + (i + 1));
int answer = input.nextInt();
if(answer<0)
{
negArray[negCount++] = answer;
}
else
{
if (answer % 2 == 0)
{
evenArray[evenCount++] = answer;
}
else
{
oddArray[oddCount++] = answer;
}
}
}
System.out.println(showArray(evenArray));
System.out.println(showArray(oddArray));
System.out.println(showArray(negArray));
}
}
showArray is void, it does not return anything. And, on inspection, it prints in the method itself. So this
System.out.println(showArray(evenArray));
System.out.println(showArray(oddArray));
System.out.println(showArray(negArray));
should just be
showArray(evenArray);
showArray(oddArray);
showArray(negArray);
Update: Thank you so much for all your input! I figured out that my low returns all 0s because java initializes all integers 0 so I changed it to int lowScore [] = new int [] {100, 100, 100, 100, 100}. The problem with findAvg is that in main i created an array of student [40] but the file only contains 15 students, which is why I cannot use a.length to find average. I've added codes to count the number of lines.
I am working on an assignment about reading a txt file of student ID along with their 5 quiz scores. The assignment is asking to read those scores up to 40 students and calculate the high, low and average for each quiz.
Sample output:
Stud Quiz1 Quiz2 Quiz3 Quiz4 Quiz5
1234 90 100 90 98 80
1243 92 92 90 98 70
High Score: 92 100 90 98 80
Low Score: 90 92 90 98 70
Average Score: 91 96 90 98 75
I've created 4 classes: student class for ID and scores, statistics class to calculate high, low and average, util class for read file function, and driver class for the main.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.StringTokenizer;
class Student {
private int SID;
private int scores[] = new int[5];
public int getSID() {
return SID;
}
public void setSID(int sID) {
SID = sID;
}
public int getScores(int index) {
return scores[index];
}
public void setScores(int[] scores) {
this.scores = scores;
}
public void printSID() {
System.out.println(SID);
}
public void printScores() {
for (int x : scores) {
System.out.println(x);
}
}
}
class Statistics {
private final int[] lowscores = new int[5];
private final int[] highscores = new int[5];
private final float[] avgscores = new float[5];
public void findlow(Student[] a) {
for (Student stu : a) {
for (int i = 0; i < 5; i++) {
lowscores[i] = Math.min(lowscores[i], stu.getScores(i));
}
}
}
public void findhigh(Student[] a) {
for (Student stu : a) {
for (int i = 0; i < 5; i++) {
highscores[i] = Math.max(highscores[i], stu.getScores(i));
}
}
}
public void findavg(Student[] a) {
int[] sum = new int[5];
for (Student stu : a) {
for (int i = 0; i < 5; i++) {
sum[i] += stu.getScores(i);
avgscores[i] = sum[i] / a.length;
}
}
}
public void printLow() {
for (int x : lowscores) {
System.out.println("Low Score " + x);
}
}
public void printHigh() {
for (int x : highscores) {
System.out.println("High Score " + x);
}
}
public void printAvg() {
for (float x : avgscores) {
System.out.println("Average " + x);
}
}
}
class Util {
static Student[] readFile(String filename, Student[] stu) {
try {
FileReader file = new FileReader(filename);
BufferedReader buff = new BufferedReader(file);
int count = 0;
boolean eof = false;
while (!eof) {
String line = buff.readLine();
if (line == null)
break;
else {
System.out.println(line);
if (count > 0) {
StringTokenizer st = new StringTokenizer(line);
for (int i = 0; i < stu.length; i++) {
stu[i] = new Student();
}
stu[count - 1].setSID(Integer.parseInt(st.nextToken()));
int scores[] = new int[5];
int scoreCount = 0;
while (st.hasMoreTokens()) {
scores[scoreCount] = Integer.parseInt(st.nextToken());
scoreCount++;
stu[count - 1].setScores(scores);
}
}
}
count++;
}
buff.close();
} catch (IOException e) {
System.out.println("Error -- " + e.toString());
}
return stu;
}
}
public class Driver{
public static void main(String[] args) {
Student lab4[] = new Student[40];
lab4 = Util.readFile("C:\\lab4.txt", lab4);
Statistics statlab4 = new Statistics();
statlab4.findlow(lab4);
statlab4.findhigh(lab4);
statlab4.findavg(lab4);
statlab4.printLow();
statlab4.printHigh();
statlab4.printAvg();
}
}
The program reads an input file lab4.txt which includes 1 line of header and 15 lines of student records. The program runs but does not calculate the high low and average correctly. I know my calculation for average might be wrong; but I don't know why high and low don't work.
Please help me. Thank you!
For the find average, you shouldn't divide by a.length every iteration.
public void findavg(Student []a) {
int []sum = new int [5];
for(Student stu: a) {
for(int i=0; i<5; i++) {
sum[i] += stu.getScores(i);
}
}
for(int i=0; i<5; i++) {
avgscores[i] = sum[i] / a.length;
}
}
The min and max seems fine.
Not going to rewrite your code for you, just going to ask some questions because I think some people are still a bit confused about your purpose:
Is the purpose of the findAvg method to find the average of all the students marks for a particular test? Or to find the student's average mark for all of their tests?
Moving the Statistics class inside the methods of the Student class (as done by some of the other answers) would work if the latter is your goal, but I wouldn't mind keeping them separate if you're going for the former.
If you're trying to find the highest mark of a group of students, then I'd get them all into an Array or ArrayList and then try an ascending sort (or do them both at the same time).
public float avgCalculate(Student [] a, int testnumber){
float sum = 0.0f;
for (Student s: a){
sum = sum + s.getScores[testnumber];
}
float average = (sum / a.length);
return average;
}
Code is completely untested, so make sure it works and get back to me. It should calculate the average scores of a bunch of students (a) on a specific test (test number). Hopefully you can extrapolate the rest of the code (you may need to modify your other classes a bit etc.) For the highs and lows consider using the Arrays.sort() library method.
Since you've mentioned the Statistics class is required, I've taken another crack at your issue. And I see that when you calculate the highs and lows, the first loop is the students. Instead, make the first loop for the appropriate array, like so:
public void findLow(Student[] a) {
for (int i = 0; i < 5; i++)
for (Student stu : a)
lowScores[i] = Math.min(stu.getScore(i), lowScores[i]);
}
What this then does is:
for each low score you want to find:
for each student that took the quiz:
if this student's score is lower, set that as the lowest
Apply the same logic to your findHigh method.
For your findAvg method, as previously stated, don't divide in every iteration:
public void findAvg(Student[] a) {
for (int i = 0; i < 5; i++) {
for (Student s : a) {
avgScores[i] += s.getScore(i);
}
avgScores[i] /= a.length;
}
}
I am new to Java and I needed dynamic Array ... all of thing I found that's for dynamic Array we should use "Array List' that's ok but when I want the indexes to be the power of X that given from input , I face ERORR ! .. the indexes are unclear and the are not specified what is the first or 2th power ! .... can anyone help me how solve it?
public static void main(String[] args) throws Exception {
Scanner Reader = new Scanner(System.in);
ArrayList<Float> Zarayeb = new ArrayList<Float>();
Float s ;
int m;
System.out.print("Add Count of equation Sentences : ");
int N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(0 , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Add Count of equation Sentences : ");
N = Reader.nextInt();
if (N == 0)
return;
for (int i = 0; i < N ; i++) {
s = Reader.nextFloat() ;
System.out.print("x^");
m = Reader.nextInt();
if (Zarayeb.get(m)== null)
Zarayeb.add(m , s);
else{
Float l ;
l = Zarayeb.get(m);
Zarayeb.add (m , l+s);
}
if (i < N-1)
System.out.print("\r+");
}
System.out.print("Enter X: ");
float X = Reader.nextFloat();
float Sum = 0;
for (int i = 0; i < Zarayeb.size();i++) {
Sum += (Zarayeb.get(i) * Math.pow(X,i));
}
System.out.println("\nThe final answer is : " + Sum);
First I refactored your code a bit to make sense of it:
Main class with the top level logic:
import java.util.Scanner;
public class Main {
private Scanner scanner;
private final Totals totals = new Totals();
public static void main(final String[] args) {
final Main app = new Main();
app.run();
}
private void run() {
scanner = new Scanner(System.in);
try {
readAndProcessEquationSentences();
} finally {
scanner.close();
}
}
private void readAndProcessEquationSentences() {
readSentences(true);
readSentences(false);
System.out.println("The final answer is : " + totals.calculateSum(readBaseInput()));
}
private void readSentences(final boolean useInitialLogic) {
System.out.print("Enter number of equation sentences:");
final int numberOfSentences = scanner.nextInt();
if (numberOfSentences == 0) {
throw new RuntimeException("No sentences");
}
for (int i = 0; i < numberOfSentences; i++) {
Sentence sentence = Sentence.read(scanner);
if (useInitialLogic) {
totals.addInitialSentence(sentence);
} else {
totals.addNextSentence(sentence);
}
if (i < numberOfSentences - 1) {
System.out.print("\r+");
}
}
}
private float readBaseInput() {
System.out.print("Enter base: ");
return scanner.nextFloat();
}
}
Sentence class which represents one equation sentence entered by the user:
import java.util.Scanner;
public class Sentence {
private Float x;
private int y;
public static Sentence read(final Scanner scanner) {
final Sentence sentence = new Sentence();
System.out.println("Enter x^y");
System.out.print("x=");
sentence.x = scanner.nextFloat();
System.out.println();
System.out.print("y=");
sentence.y = scanner.nextInt();
System.out.println();
return sentence;
}
public Float getX() {
return x;
}
public int getY() {
return y;
}
}
Totals class which keeps track of the totals:
import java.util.ArrayList;
import java.util.List;
public class Totals {
private final List<Float> values = new ArrayList<Float>();
public void addInitialSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
addToStart(sentence);
} else {
addToValue(sentence);
}
}
private void addToStart(final Sentence sentence) {
values.add(0, sentence.getX());
}
public void addNextSentence(final Sentence sentence) {
if (values.size() <= sentence.getY()) {
values.add(sentence.getY(), sentence.getX());
} else {
addToValue(sentence);
}
}
private void addToValue(final Sentence sentence) {
Float total = values.get(sentence.getY());
total = total + sentence.getX();
values.add(sentence.getY(), total);
}
public float calculateSum(final float base) {
float sum = 0;
for (int i = 0; i < values.size(); i++) {
sum += (values.get(i) * Math.pow(base, i));
}
return sum;
}
}
I don't have the foggiest idea what this is supposed to do. I named the variables according to this foggy idea.
You are letting the user input values in two separate loops, with a slightly different logic I called 'initial' and 'next'.
In the initial loop you were doing this:
if (Zarayeb.get(m) == null)
Zarayeb.add(0 , s);
In the next loop this:
if (Zarayeb.get(m) == null)
Zarayeb.add(m , s);
There are problems with this because the ArrayList.get(m) will throw an IndexOutOfBoundException if m is out or range. So I changed that to the equivalent of:
if (Zarayeb.size() <= m) {
....
}
However, in the 'next' case this still does not solve it. What should happen in the second loop when an 'm' value is entered for which no element yet exists in the ArrayList?
Why do you need to enter sentences in two loops?
What is the logic supposed to achieve exactly?
I submitted one code in code chef but it's giving wrong answer even if it's correct
can anybody help me to identify that please.
I have tried so many inputs and calculated manually and they are correct so why they gave me wrong answer.
so,anybody who can find the TEST Case which give incorrect output by this code ?.
Here is Problem definition.
import java.util.Scanner;
import java.lang.Math;
class Codechef {
static int get(int n,int i,int digit)
{
int p;
p=(int)Math.pow(10,i-1);
n=n/p;
return n%10;
}
static boolean check_pal(int n)
{
int digit;
digit=(int) (Math.log10(n)+1);
int a=0,b=0,i,j,p;
int sum=0;
for(i=1,j=digit-1 ; i<=digit ; i++,j-- )
{
a=get(n,i,digit);
sum+=a*Math.pow(10,j);
}
if(sum==n)
return true;
else
return false;
}
static int reverse(int n)
{
int digit;
digit=(int) (Math.log10(n)+1);
int a=0,b=0,i,j,p;
int sum=0;
for(i=1,j=digit-1 ; i<=digit ; i++,j-- )
{
a=get(n,i,digit);
sum+=a*Math.pow(10,j);
}
return n+sum;
}
public static void main(String[] args) {
try{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
if(n<10 || n>999){
System.out.println("NONE");
return;
}
boolean c;
for(int i=1 ; i<=100 ; i++)
{
c=check_pal(n);
if(c==true)
{
System.out.println(n);
return;
}
n=reverse(n);
}
System.out.println("NONE");
}
catch(Exception e)
{
System.out.println("NONE");
}
}
}
Here is one more output.
for 99 it gives 99 and which is correct as it's palindrome.
For 89 (or 98 for that matter), your code returns "NONE", although you reach the answer 8813200023188 after only 24 steps.
Another case is that for 177 and 276 you should get 8836886388 instead of NONE
I didn't debug your code, I just wrote a program that does the same, and compared the output my program gave to the one your program gave. Since you just requested a testcase, that should suffice :) My gutfeeling is that you overflow... an int is not large enough to hold the answer in all cases.
Happy bughunting.
Edit (on Request) with my code.
I didn't change your code, except that I extracted your logic into a getResult(integer) methode so that I could bypass the scanning of the input and simply return a string as result. It prints out all the differences between our versions. I used BigInteger as the type to hold my results.
public class Main {
public static void main(String[] args) {
Main m = new Main();
for (int i=10; i < 1000; i++) {
String myResult = null;
String hisResult = null;
try {
myResult = m.getResultAsString(i);
} catch (Exception e){
System.out.println("Your code threw an exception for " + i);
}
try{
hisResult = Codechef.getResult(i);
} catch (Exception e){
System.out.println("His code threw an exception for " + i);
}
if (myResult != null && hisResult != null && ! myResult.equals(hisResult)) {
System.out.println("For " + i + " you have " + myResult + " but he has " + hisResult);
}
}
}
public String getResultAsString(int inputNumber) {
BigInteger res = getResultAsBigInteger(new BigInteger(""+inputNumber));
if (res != null) {
return res.toString();
} else {
return "NONE";
}
}
public BigInteger getResultAsBigInteger(BigInteger inputNumber) {
int numberOfSteps = 0;
BigInteger currentValue = inputNumber;
while (numberOfSteps < 101 && ! isPalindrome(currentValue)) {
numberOfSteps++;
currentValue = currentValue.add(reverseDigits(currentValue));
}
return numberOfSteps < 101 ? currentValue : null;
}
public boolean isPalindrome(BigInteger number) {
return number.equals(reverseDigits(number));
}
public BigInteger reverseDigits(BigInteger input) {
String inputString = input.toString();
String output = "";
for (int i = inputString.length() - 1; i >= 0; i--)
{
output += inputString.charAt(i);
}
return new BigInteger(output);
}
}
There is an overflow error in your code.
for input 89 it's not working as #Yves V. said
Suggestion is to use BigInteger class of lang.Match it will be useful to eliminate this overflow error.
I'm solving Uva's 3n+1 problem and I don't get why the judge is rejecting my answer. The time limit hasn't been exceeded and the all test cases I've tried have run correctly so far.
import java.io.*;
public class NewClass{
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
int maxCounter= 0;
int input;
int lowerBound;
int upperBound;
int counter;
int numberOfCycles;
int maxCycles= 0;
int lowerInt;
BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
String line = consoleInput.readLine();
String [] splitted = line.split(" ");
lowerBound = Integer.parseInt(splitted[0]);
upperBound = Integer.parseInt(splitted[1]);
int [] recentlyused = new int[1000001];
if (lowerBound > upperBound )
{
int h = upperBound;
upperBound = lowerBound;
lowerBound = h;
}
lowerInt = lowerBound;
while (lowerBound <= upperBound)
{
counter = lowerBound;
numberOfCycles = 0;
if (recentlyused[counter] == 0)
{
while ( counter != 1 )
{
if (recentlyused[counter] != 0)
{
numberOfCycles = recentlyused[counter] + numberOfCycles;
counter = 1;
}
else
{
if (counter % 2 == 0)
{
counter = counter /2;
}
else
{
counter = 3*counter + 1;
}
numberOfCycles++;
}
}
}
else
{
numberOfCycles = recentlyused[counter] + numberOfCycles;
counter = 1;
}
recentlyused[lowerBound] = numberOfCycles;
if (numberOfCycles > maxCycles)
{
maxCycles = numberOfCycles;
}
lowerBound++;
}
System.out.println(lowerInt +" "+ upperBound+ " "+ (maxCycles+1));
}
}
Are you making sure to accept the entire input? It looks like your program terminates after reading only one line, and then processing one line. You need to be able to accept the entire sample input at once.
I faced the same problem. The following changes worked for me:
Changed the class name to Main.
Removed the public modifier from the class name.
The following code gave a compilation error:
public class Optimal_Parking_11364 {
public static void main(String[] args) {
...
}
}
Whereas after the changes, the following code was accepted:
class Main {
public static void main(String[] args) {
...
}
}
This was a very very simple program. Hopefully, the same trick will also work for more complex programs.
If I understand correctly you are using a memoizing approach. You create a table where you store full results for all the elements you have already calculated so that you do not need to re-calculate results that you already know (calculated before).
The approach itself is not wrong, but there are a couple of things you must take into account. First, the input consists of a list of pairs, you are only processing the first pair. Then, you must take care of your memoizing table limits. You are assuming that all numbers you will hit fall in the range [1...1000001), but that is not true. For the input number 999999 (first odd number below the upper limit) the first operation will turn it into 3*n+1, which is way beyond the upper limit of the memoization table.
Some other things you may want to consider are halving the memoization table and only memorize odd numbers, since you can implement the divide by two operation almost free with bit operations (and checking for even-ness is also just one bit operation).
Did you make sure that the output was in the same order specified in the input. I see where you are swapping the input if the first input was higher than the second, but you also need to make sure that you don't alter the order it appears in the input when you print the results out.
ex.
Input
10 1
Output
10 1 20
If possible Please use this Java specification : to read input lines
http://online-judge.uva.es/problemset/data/p100.java.html
I think the most important thing in UVA judge is 1) Get the output Exactly same , No Extra Lines at the end or anywhere . 2) I am assuming , Never throw exception just return or break with No output for Outside boundary parameters.
3)Output is case sensitive 4)Output Parameters should Maintain Space as shown in problem
One possible solution based on above patterns is here
https://gist.github.com/4676999
/*
Problem URL: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=36
Home>Online Judge > submission Specifications
Sample code to read input is from : http://online-judge.uva.es/problemset/data/p100.java.html
Runtime : 1.068
*/
import java.io.*;
import java.util.*;
class Main
{
static String ReadLn (int maxLg) // utility function to read from stdin
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main (String args[]) // entry point from OS
{
Main myWork = new Main(); // create a dinamic instance
myWork.Begin(); // the true entry point
}
void Begin()
{
String input;
StringTokenizer idata;
int a, b,max;
while ((input = Main.ReadLn (255)) != null)
{
idata = new StringTokenizer (input);
a = Integer.parseInt (idata.nextToken());
b = Integer.parseInt (idata.nextToken());
if (a<b){
max=work(a,b);
}else{
max=work(b,a);
}
System.out.println (a + " " + b + " " +max);
}
}
int work( int a , int b){
int max=0;
for ( int i=a;i<=b;i++){
int temp=process(i);
if (temp>max) max=temp;
}
return max;
}
int process (long n){
int count=1;
while(n!=1){
count++;
if (n%2==1){
n=n*3+1;
}else{
n=n>>1;
}
}
return count;
}
}
Please consider that the integers i and j must appear in the output in the same order in which they appeared in the input, so for:
10 1
You should print
10 1 20
package pandarium.java.preparing2topcoder;/*
* Main.java
* java program model for www.programming-challenges.com
*/
import java.io.*;
import java.util.*;
class Main implements Runnable{
static String ReadLn(int maxLg){ // utility function to read from stdin,
// Provided by Programming-challenges, edit for style only
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main(String args[]) // entry point from OS
{
Main myWork = new Main(); // Construct the bootloader
myWork.run(); // execute
}
public void run() {
new myStuff().run();
}
}
class myStuff implements Runnable{
private String input;
private StringTokenizer idata;
private List<Integer> maxes;
public void run(){
String input;
StringTokenizer idata;
int a, b,max=Integer.MIN_VALUE;
while ((input = Main.ReadLn (255)) != null)
{
max=Integer.MIN_VALUE;
maxes=new ArrayList<Integer>();
idata = new StringTokenizer (input);
a = Integer.parseInt (idata.nextToken());
b = Integer.parseInt (idata.nextToken());
System.out.println(a + " " + b + " "+max);
}
}
private static int getCyclesCount(long counter){
int cyclesCount=0;
while (counter!=1)
{
if(counter%2==0)
counter=counter>>1;
else
counter=counter*3+1;
cyclesCount++;
}
cyclesCount++;
return cyclesCount;
}
// You can insert more classes here if you want.
}
This solution gets accepted within 0.5s. I had to remove the package modifier.
import java.util.*;
public class Main {
static Map<Integer, Integer> map = new HashMap<>();
private static int f(int N) {
if (N == 1) {
return 1;
}
if (map.containsKey(N)) {
return map.get(N);
}
if (N % 2 == 0) {
N >>= 1;
map.put(N, f(N));
return 1 + map.get(N);
} else {
N = 3*N + 1;
map.put(N, f(N) );
return 1 + map.get(N);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
while(scanner.hasNextLine()) {
int i = scanner.nextInt();
int j = scanner.nextInt();
int maxx = 0;
if (i <= j) {
for(int m = i; m <= j; m++) {
maxx = Math.max(Main.f(m), maxx);
}
} else {
for(int m = j; m <= i; m++) {
maxx = Math.max(Main.f(m), maxx);
}
}
System.out.println(i + " " + j + " " + maxx);
}
System.exit(0);
} catch (Exception e) {
}
}
}