(URI) Soma de Ímpares Consecutivos II - Solução 2

Versão utilizando a Soma dos Termos de uma Progressão Aritmética, objetivando a eliminação do loop.

Para isto, precisamos saber o primeiro e o último valores ímpares a serem considerados e a quantidade de elementos que existirá nesta PA.

Veja mais sobre Progressão Aritmética aqui.

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

class Main  {
    public static void main(String[] args) throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
       
        int entradas = leitor(br);
       
        for (int i = 0; i < entradas; i++) {
            int x = leitor(br);
            int y = leitor(br);
           
            if (x != y) {
                int maior = Math.max(x, y);
                int menor = Math.min(x, y);
           
                int primeiro = -1;
                int ultimo = -1;
                if ((menor+1)%2 == 1) { // pega primeiro valor impar
                    primeiro = menor+1;
                }
                else {
                    primeiro = menor+2;
                }

                if ((maior-1)%2 == 1) { // pega ultimo valor impar
                    ultimo = maior-1;
                }
                else {
                    ultimo = maior-2;
                }

                int n = (ultimo-(primeiro-2))/2; // an = a1 + (n-1) * r
               
                bw.write((n*(primeiro+ultimo))/2+"\n");
            }
            else {
                bw.write("0\n");
            }
        }

        bw.flush();       
        bw.close();
    }

    static int leitor(BufferedReader br) throws NumberFormatException, IOException {
       int n;
       int resp = 0;
       int sinal = 1;
       while (true) {
           n = br.read();
           if (n >= '0' && n <= '9') break;
           if (n == '-') sinal = -1;
           if (n == '+') sinal = 1;
       }
       while (true) {
           resp = resp*10 + n-'0';
           n = br.read();
           if (n < '0' || n > '9') break;
       }

       return resp*sinal;
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução