Calculate a triangular number
Calculate the nth triangular number, the sum of all integers from 1 through a non-negative n.
Course progress
Problem 71 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
n = 10
Expected output
55
What is happening?
The sum 1 + 2 + ... + 10 can be calculated as 10 x 11 / 2, which equals 55.
Solution strategy
Build the right mental model
Use n times n plus one divided by two, dividing the even factor first to keep the intermediate product smaller.
Core concepts
arithmetic · integer overflow
Complexity
Time O(1), space O(1).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for triangular-number
using System;
class Program
{
static long TriangularNumber(int number)
{
if (number < 0) throw new ArgumentOutOfRangeException("number");
long first = number;
long second = first + 1;
if (first % 2 == 0) first /= 2;
else second /= 2;
return first * second;
}
static void Main()
{
Console.WriteLine(TriangularNumber(10));
}
}Knowledge check
Questions students often ask
What is the main idea behind calculate a triangular number?
Use n times n plus one divided by two, dividing the even factor first to keep the intermediate product smaller.
What is the time and space complexity of this solution?
Time O(1), space O(1).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.