Why Do We Sometimes Write LL in C++?

Why do we sometimes write LL in C++?

Why do we sometimes write <span>LL</span> in C++?

When writing C++, you often see others adding <span>LL</span> after numbers, for example, <span>1000000000000LL</span>. As a beginner, you might wonder: can’t we just write <span>1000000000000</span> directly? The answer is — not necessarily.

The story begins with an “overflow”

Imagine a requirement: to calculate the area of a rectangle. Both width and height are in the hundred-thousand range:

<span>#include <bits/stdc++.h></span><span>using</span> <span>namespace</span> <span>std;</span> <span>int</span> <span>main() {</span><span> </span><span>int</span> <span>w = 100000, h = 100000;</span><span> </span><span>long</span> <span>long</span> <span>area = w * h;</span> <span> </span><span>cout << </span><span>"ans1 = "</span> <span><< area << endl;</span> <span>}</span>

When the result is printed,

<span>ans1 = 1410065408</span>

the area is completely incorrect! Where did the problem lie?

  • <span>w</span> and <span>h</span> are of type <span>int</span>.

  • In C++, multiplying two <span>int</span>s results in an <span>int</span> as well, causing an overflow in the intermediate steps.

  • By the time the result is cast to <span>long long</span>, it’s already too late.

So someone wrote it like this:

<span>long</span> <span>long</span> <span>area = 1LL * w * h;</span>

Here, <span>1LL</span> promotes the entire expression to <span>long long</span><span>, ensuring that the calculation is correct.</span>

So, what does <span>LL</span> actually do?

In C++, numeric literals (like <span>123456</span>) are of type <span>int</span> by default. If you add <span>LL</span>, it becomes of type <span>long long</span>.

So:

  • <span>1000</span> is <span>int</span>.

  • <span>1000L</span> is <span>long</span>.

  • <span>1000LL</span> is <span>long long</span>.

It may seem like a small suffix, but it directly determines the precision of the computation.

Common usages

  1. Preventing intermediate overflow

    long long sum = 1LL * n * (n + 1) / 2;

    If <span>n</span> is on the order of <span>10^9</span>, without <span>LL</span>, it will overflow in no time.

  2. Defining large constants

    const long long LIMIT = 1000000000000LL;

    This clearly indicates that it is a <span>long long</span> constant, avoiding type ambiguity.

  3. Essential pattern for algorithm problems Whenever dealing with squares, multiplications, or combinations, writing a <span>1LL</span> can essentially save your life.

In summary

<span>LL</span> is like putting a “safety helmet” on a number. In scenarios requiring large number calculations, it prevents unexpected overflows and makes results more reliable. Therefore, when encountering numbers like <span>10^9</span> or <span>10^12</span>, adding an <span>LL</span> is both a habit and a safeguard.

Leave a Comment