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
