(URI) Soma Natural - Solução


Tendo em vista que no enunciado as entradas A e B podem variar de 1 a 109, então uma entrada possível é:

1 1000000000

O que nos daria como resposta o valor 500000000500000000, que não é comportado por um int. Por este motivo, a resposta é um tipo long.



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

class Main {
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main processando = new Main();
        processando.processa();
      
        System.exit(0);
    }
  
    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;
    }
  
    void processa() throws NumberFormatException, IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      
        int a = leitor(br);
        int b = leitor(br);
      
        long somatorio = ((long)b*(b+1))/2 - ((long)(a-1)*((a-1)+1))/2;
      
        System.out.println(somatorio);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução