Input
The input consists of a single integer N that is not greater than 10000 by it's absolute value.
Output
Write a single integer number that is the sum of all integer numbers lying between 1 and N inclusive.
Sample
Input:
-3
Output
-5
http://acm.timus.ru/problem.aspx?space=1&num=1068
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Problema1068
{
public static void main( String args[] ) throws Exception
{
BufferedReader br = new BufferedReader( new InputStreamReader( System.in ) );
int numero = Integer.parseInt( br.readLine() );
// Si el numero es positivo la retornamos F(n), donde F(n) indica la
// suma de todos los numeros en el intervalo de 1 hasta n
if( numero > 0 )
System.out.println( sumatoria( numero ) );
// Si el numero es negativo, la respuesta sera la suma:
// -n + -(n-1) + ... + -1 + 0 + 1 = - ( n + (n-1) + ... + 1 ) + 0 + 1
// Se puede apreciar que esa suma es igual a -F( -n ) + 1
else
System.out.println( -sumatoria( -numero ) + 1 );
}
public static int sumatoria( int N )
{
// Aplicamos la formula F(n) = n * ( n + 1 ) / 2
// Para mejorar la eficiencia, realiamoz antes la division,
// para que los numeros a multiplicar sean mas pequeños
if( ( N & 1 ) == 0 )
return ( N >> 1 ) * ( N + 1 );
else
return N * ( ( N + 1 ) >> 1 );
}
}
No hay comentarios:
Publicar un comentario