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,

  1. Define a function named sumOfNaturalNumbers that takes one parameter n of type int.
  2. Use the formula n * (n + 1) / 2 to calculate the sum of the first N natural numbers.
  3. Return the calculated sum.
  4. 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