LearnFrenzy
Sign in Take a free test

Input/Output with cin and cout · Input/Output Programs · Question 10

Fast input: sum of many numbers with sync_with_stdio in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

Read n and then n integers as fast as possible (competitive-programming style) and print their sum, which may exceed the int range.

Solution
main.cpp
#include <iostream>

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    int n;
    std::cin >> n;
    long long sum = 0;
    for (int i = 0; i < n; ++i) {
        long long x;
        std::cin >> x;
        sum += x;
    }
    std::cout << sum << '\n';
    return 0;
}

Output Verified by compiling and running

4000000254

Turning off stdio synchronisation and untying cin from cout removes the two biggest costs of iostreams. The sum is kept in long long because it exceeds 2,147,483,647.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links