# Finding sum of first n natural numbers in PL/SQL

• Last Updated : 07 Jul, 2018

Prerequisite PL/SQL introduction
In PL/SQL code groups of commands are arranged within a block. A block group related declarations or statements. In declare part, we declare variables and between begin and end part, we perform the operations.
Given a positive integer n and the task is to find the sum of first n natural number.
Examples:

```Input: n = 3
Output: 10

Input: n = 2
Output: 4
```

Approach is to take digits form 1 and to n and summing like done below-

```Sum of first natural number: 1
Sum of first and second natural number: 1 + 2 = 3
Sum of first, second and third natural number = 1 + 2 + 3 = 6```

Below is the required implementation:

 `--declaration section ``DECLARE` `  ``x NUMBER; ``  ``n NUMBER; ``  ``i NUMBER; ``   ` `  ``--function for finding sum ``  ``FUNCTION` `Findmax(n ``IN` `NUMBER) ``    ``RETURN` `NUMBER ``  ``IS` `    ``sums NUMBER := 0; ``  ``BEGIN` `   ` `    ``--for loop for n times iteration ``    ``FOR` `i ``IN` `1..n ``    ``LOOP ``      ``sums := sums + i*(i+1)/2; ``    ``END` `LOOP; ``    ``RETURN` `sums; ``  ``END``; ``  ``BEGIN` `   ` `    ``--driver code ``    ``n := 4; ``    ``x := findmax(n); ``    ``dbms_output.Put_line(``'Sum: '` `    ``|| x); ``  ``END``; ``   ` `  ``--end of Program`

Output:

`Sum: 20`

Time complexity = O(n)

An efficient solution is to use direct formula n(n+1)(n+2)/6

Mathematically, we need to find, Σ ((i * (i + 1))/2), where 1 <= i <= n
So, lets solve this summation,

```Sum = Σ ((i * (i + 1))/2), where 1 <= i <= n
= (1/2) * Σ (i * (i + 1))
= (1/2) * Σ (i2 + i)
= (1/2) * (Σ i2 + Σ i)

We know Σ i2 = n * (n + 1) * (2*n + 1) / 6 and
Σ i = n * ( n + 1) / 2.
Substituting the value, we get,
Sum = (1/2) * ((n * (n + 1) * (2*n + 1) / 6) + (n * ( n + 1) / 2))
= n * (n + 1)/2 [(2n + 1)/6 + 1/2]
= n * (n + 1) * (n + 2) / 6```

Below is the required implementation:

 `--declaration section ``DECLARE` `  ``x NUMBER; ``  ``n NUMBER; ``   ` `  ``--utility function ``  ``FUNCTION` `Findmax(n ``IN` `NUMBER) ``    ``RETURN` `NUMBER ``  ``IS` `    ``z NUMBER; ``  ``BEGIN` `   ` `    ``-- formula for finding sum ``    ``z := (n * (n + 1) * (n + 2)) / 6; ``    ``RETURN` `z; ``  ``END``; ``  ``BEGIN` `    ``n := 4; ``    ``x := findmax(n); ``    ``dbms_output.Put_line(``' Sum: '` `    ``|| x); ``  ``END``; ``   ` `  ``--end of program`

Output:

`Sum: 20`

Time complexity = O(1)

My Personal Notes arrow_drop_up