Competitive programming

Stage 1 · Lesson 7 of 7

Integer overflow and choosing types

C++ for contests

An int holds values up to about 2.1 * 10^9, and a long long up to about 9.2 * 10^18. Sums of many large values, and products of two values around 10^5, already exceed int. does not give an error: the value silently wraps around and your answer is wrong.

Multiplying two int variables overflows before the result is stored, even if you store it in a long long, so write 1LL * a * b. Doubles (floating point numbers) cannot hold every large integer exactly, so avoid them for exact answers. A common habit is to use long long for every sum and answer.

Common trapthinking the answer fits in int because the input does.

A question to check yourself, an AI practice session and 1 cheat sheet entry come with the full roadmap. Unlock

Resources for this stage

Start with· follow one of these

  • CourseFree
    LearnCpp.com

    LearnCpp.com · Beginner

    Free and thorough: read the chapters on vectors, references, lambdas and the standard library if C++ is new to you

  • BookFree
    Competitive Programmer's Handbook

    Antti Laaksonen · Beginner

    Chapter 1 covers C++ for contests, input and output and working with numbers; Chapter 2 covers complexity

Practise

  • Start with the Introductory Problems section: short tasks that exercise loops, strings and the STL

  • Filter the problem set to rating 800 and solve a few each day to get used to contest input and output

Keep handy

  • Keep it open for exact signatures and complexities of vector, set, map, sort and lower_bound

Also worth your time

Mark this stage as not done?