liveBook · Manning

Triangle number

As explained in Learn C++ by Example

A triangle number is a number in the sequence formed by summing the positive integers from one through its position.

A triangle number sums the positive integers from 1 through its position: 1, 3, 6, 10, 15, and so forth. The name comes from arranging that many snooker balls in triangular rows. section 9.1

Build the sequence in C++ with standard numeric algorithms:

  • Create a vector with the requested count of elements. section 9.1
  • Use std::iota to fill it with 1, 2, 3, and so on. section 9.1
  • Use std::partial_sum in place to turn those values into cumulative sums. section 9.1

Checking the sequence

For the first 20 values, std::adjacent_difference reconstructs 1 through 20, and applying it again produces only 1s. std::all_of and std::count verify these properties; a mutable lambda also checks each value against n * (n + 1) / 2. section 9.1.1 section 9.1.3

Exploring patterns

Transforming each number into '.' for odd and '*' for even reveals the repeating parity pattern. A std::map can tally the final digits of the first 20 values, supporting a slot-machine payout experiment. section 9.1.4 section 9.3

Listing 9.1 Making the first few triangle numbers
#include <numeric>
#include <vector>
constexpr std::vector<int> make_triangle_numbers(int count)
{
    std::vector<int> numbers(count);                                      #1
    std::iota(numbers.begin(), numbers.end(), 1);                         #2
    std::partial_sum(numbers.begin(), numbers.end(), numbers.begin());    #3
    return numbers;
}

View the complete constexpr make_triangle_numbers function using std::iota and std::partial_sum. section 9.1

How Learn C++ by Example covers it

How deep it goes
Explains construction, inverse-difference tests, the closed-form check, parity, final digits, and game probabilities.
Examples
Demonstrates snooker-ball rows, C++ vectors, difference tests, parity markers, digit tallies, and slot-machine payouts.
What you can do after
Builds and tests triangle-number sequences with C++ numeric algorithms, then analyzes their properties for a simple game.
How it connects
Connects triangle numbers with cumulative sums, numeric algorithms, mutable lambdas, parity, std::map, and probability.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.