Go Program to Find Sum of N Natural Numbers
In Go, you can find the sum of n natural numbers by using a loop or the formula
sum = n * (n + 1) / 2. For example, sum := n * (n + 1) / 2 calculates the sum directly.Examples
Input5
OutputSum of first 5 natural numbers is 15
Input10
OutputSum of first 10 natural numbers is 55
Input1
OutputSum of first 1 natural numbers is 1
How to Think About It
To find the sum of the first n natural numbers, think of adding all numbers from 1 up to n. You can do this by adding each number one by one using a loop, or use the simple math formula
n * (n + 1) / 2 which gives the same result instantly.Algorithm
1
Get the input number n from the user2
Calculate the sum using the formula sum = n * (n + 1) / 23
Print the sumCode
go
package main import "fmt" func main() { var n int fmt.Print("Enter a positive integer: ") fmt.Scan(&n) sum := n * (n + 1) / 2 fmt.Printf("Sum of first %d natural numbers is %d\n", n, sum) }
Output
Enter a positive integer: 5
Sum of first 5 natural numbers is 15
Dry Run
Let's trace the input 5 through the code
1
Input
User enters n = 5
2
Calculate sum
sum = 5 * (5 + 1) / 2 = 5 * 6 / 2 = 30 / 2 = 15
3
Output
Print 'Sum of first 5 natural numbers is 15'
| n | sum |
|---|---|
| 5 | 15 |
Why This Works
Step 1: Input reading
The program reads the number n from the user using fmt.Scan.
Step 2: Sum calculation
It uses the formula n * (n + 1) / 2 which adds all numbers from 1 to n efficiently.
Step 3: Output display
The program prints the result using fmt.Printf with formatted output.
Alternative Approaches
Using a loop
go
package main import "fmt" func main() { var n, sum int fmt.Print("Enter a positive integer: ") fmt.Scan(&n) for i := 1; i <= n; i++ { sum += i } fmt.Printf("Sum of first %d natural numbers is %d\n", n, sum) }
This method uses a loop to add numbers one by one, which is easy to understand but slower for very large n.
Using recursion
go
package main import "fmt" func sumNatural(n int) int { if n == 1 { return 1 } return n + sumNatural(n-1) } func main() { var n int fmt.Print("Enter a positive integer: ") fmt.Scan(&n) fmt.Printf("Sum of first %d natural numbers is %d\n", n, sumNatural(n)) }
This method uses recursion to add numbers, which is elegant but can cause stack overflow for very large n.
Complexity: O(1) time, O(1) space
Time Complexity
Using the formula, the sum is calculated in constant time without loops.
Space Complexity
Only a few variables are used, so space is constant.
Which Approach is Fastest?
The formula method is fastest; loop and recursion methods take O(n) time.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Formula | O(1) | O(1) | Fastest calculation for any n |
| Loop | O(n) | O(1) | Simple and easy to understand |
| Recursion | O(n) | O(n) | Elegant but uses more memory |
Use the formula
n * (n + 1) / 2 for the fastest and simplest sum calculation.Beginners often forget to use integer division properly or use float division causing incorrect results.