520. The sum of all

 

Find the sum of all the given numbers.

 

Input. Contains n (1 ≤ n ≤ 105) integers. Each integer does not exceed 109 in absolute value.

 

Output. Print the sum of all the given numbers.

 

Sample input

Sample output

2 3

   1      1

7

 

 

SOLUTION

read till the end of file

 

Algorithm analysis

Since n ≤ 105 and each number does not exceed 109 in absolute value, the sum of the given numbers can be up to approximately 1014. To compute the result, use the long long type.

 

Algorithm implementation

Read the input data until the end of the file. Sum up the given numbers.

 

res = 0;

while(scanf("%lld",&n) == 1)

  res += n;

 

Print the result.

 

printf("%lld\n",res);

 

Java implementation

 

import java.util.*;

 

public class Main

{

  public static void main(String[] args)

  {

    Scanner con = new Scanner(System.in);

    long sum = 0;

    while(con.hasNext())

    {

      long val = con.nextLong();

      sum += val;

    }

    System.out.println(sum);

    con.close();

  }

}

 

Python implementation

 

import sys

 

Read the input data until the end of the file. Sum up the given numbers.

 

sum = 0

for line in sys.stdin:

  for var in line.split():

    sum = sum + int(var)

 

Print the result.

 

print(sum)

 

Python implementation – read from file

 

sum = 0

 

with open('d:\\WorkPython\\520.in', 'r') as file:

  for line in file:

    for var in line.split():

      sum += int(var)

 

print(sum)