(UVA) 100 - The 3n + 1 problem - Solução

import java.io.*;
import java.util.*;

class Main {
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main processando = new Main();
        processando.takeInput();
       
        System.exit(0);
    }

    int obtemMaximo(int numMenor, int numMaior) {
        int quantidade = 0;
        int maior = 0;
        int n = 0;
               
        for(int i = numMenor; i <= numMaior; i++) {
            n = i;
            while (n != 0) {
                if (n == 1) {
                    quantidade += 1;
                    if (quantidade > maior) {
                        maior = quantidade; 
                    }
                    quantidade = 0; 
                    n = 0;
                }
                else {
                    if (n%2 == 1) {
                        n = 3*n + 1;
                        quantidade += 1;
                    }
                    else {
                        n = n/2;
                        quantidade += 1;
                    }
                }
            }
        }
       
        return maior;
    }   
   
    void takeInput() throws NumberFormatException, IOException {
        String line = "";
        int max = 0;
        StringTokenizer tokenizer = null;
        int i = 0;
        int j = 0;
        int f = 0;
       
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
       
        while (((line = br.readLine()) != null)) {
            f = 0;
            tokenizer = new StringTokenizer(line);
            i = Integer.parseInt(tokenizer.nextToken());
            j = Integer.parseInt(tokenizer.nextToken());
            int temp;
            if (i > j) {
                f = 1;
                temp = i;
                i = j;
                j = temp;
            }
           
            max = obtemMaximo(i, j);
            if(f == 0)
                System.out.println(i + " " + j + " " + max);
            else
                System.out.println(j + " " + i + " " + max);
        }
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução