Find the Sum of First N Natural Numbers in Go
In this tutorial, we will learn how to find the sum of the first N natural numbers in Go. We will cover the basic concept and implement a function to perform the calculation.
What is the Sum of Natural Numbers
The sum of the first N natural numbers is the sum of all positive integers from 1 to N. This can be calculated using the formula:
Sum = N * (N + 1) / 2
Syntax
The syntax to find the sum of the first N natural numbers in Go is:
func sumOfNaturalNumbers(n int) int {
return n * (n + 1) / 2
}
Example 1: Finding the sum of the first N natural numbers
We can create a function to calculate the sum of the first N natural numbers using the formula.
For example,
- Define a function named
sumOfNaturalNumbers
that takes one parametern
of typeint
. - Use the formula
n * (n + 1) / 2
to calculate the sum of the first N natural numbers. - Return the calculated sum.
- In the main function, call the
sumOfNaturalNumbers
function with a sample value and print the result.
Go Program
package main
import (
"fmt"
)
func sumOfNaturalNumbers(n int) int {
return n * (n + 1) / 2
}
func main() {
// Find the sum of the first 10 natural numbers
result := sumOfNaturalNumbers(10)
// Print the result
fmt.Printf("Sum of the first 10 natural numbers is %d\n", result)
}
Output
Sum of the first 10 natural numbers is 55