Posted on by Kalkicode
Code Mathematics

Sum of natural numbers in a range

The sum of natural numbers is a fundamental mathematical concept, representing the total of all positive integers within a given range. Calculating the sum of natural numbers within a specified range is a common problem with various applications in mathematics and computer science. This article explains how to find the sum of natural numbers within a given range using a C program.

Problem Statement

Given two integers, 'first' and 'last', representing the range of natural numbers (inclusive), the problem is to calculate the sum of natural numbers within that range.

Example

For instance, if 'first' is 5 and 'last' is 10, the sum of natural numbers from 5 to 10 would be 5 + 6 + 7 + 8 + 9 + 10 = 45. Similarly, for the range from 20 to 25, the sum is 135. For the range 4 to 14, the sum is 99, and for the range 5 to 13, the sum is 81.

Idea to Solve

To solve this problem, we need to iterate through the numbers within the given range and sum them up. An efficient way to calculate the sum of natural numbers from 1 to 'n' is by using the formula (n * (n + 1)) / 2. We can extend this formula to calculate the sum of natural numbers in a given range from 'first' to 'last'.

Pseudocode

function sum_natural_number(first, last):
    if first <= 0 or last <= 0:
        return
    else if first > last:
        Swap 'first' and 'last'
        Call sum_natural_number(last, first)
    else:
        Calculate the number of elements in the range: element = (last - first)
        Calculate the sum using the formula: sum = first * (element + 1) + (element * (element + 1) / 2)
        Print "Sum of natural numbers from", first, "to", last, "is", sum

function main():
    sum_natural_number(5, 10)
    sum_natural_number(20, 25)
    sum_natural_number(4, 14)
    sum_natural_number(5, 13)

Algorithm Explanation

  1. The sum_natural_number function takes two parameters: 'first' and 'last'.
  2. It checks if either 'first' or 'last' is less than or equal to 0, and if so, it returns without performing any calculations.
  3. If 'first' is greater than 'last', it swaps the values of 'first' and 'last' and then calls the function again with the swapped values to ensure a valid range.
  4. If 'first' is less than or equal to 'last', it calculates the number of elements in the range (element = last - first).
  5. Using the formula (first * (element + 1)) + ((element) * (element + 1) / 2), it calculates the sum of natural numbers in the given range.
  6. It prints the calculated sum along with the provided range.
  7. The main function tests the sum_natural_number function with different values.

Code Solution

// C Program
// Sum of natural numbers in given range
#include <stdio.h>

//Calculating the sum of n natural numbers from two numbers
void sum_natural_number(int first, int last)
{
	if (first <= 0 || last <= 0)
	{
		return;
	}
	else if (first > last)
	{
		//Make a valid range
		sum_natural_number(last, first);
	}
	else
	{
		//First count  number elements
		int element = (last - first);
		//Formula
		// first *(total_element+1) * ((total_element) * (total_element + 1) / 2)
		long long int sum = first * (element + 1) + ((element) * (element + 1) / 2);
		//Display calculated result
		printf("Sum of natural numbers from ( %d to %d ) is %lld\n", first, last, sum);
	}
}
int main()
{
	//Test case
	sum_natural_number(5, 10);
	sum_natural_number(20, 25);
	sum_natural_number(4, 14);
	sum_natural_number(5, 13);
	return 0;
}

Output

Sum of natural numbers from ( 5 to 10 ) is 45
Sum of natural numbers from ( 20 to 25 ) is 135
Sum of natural numbers from ( 4 to 14 ) is 99
Sum of natural numbers from ( 5 to 13 ) is 81
// Java Program 
// Sum of natural numbers in given range
class MyMaths
{
	//Calculating the sum of n natural numbers from two numbers
	public void sum_natural_number(int first, int last)
	{
		if (first <= 0 || last <= 0)
		{
			return;
		}
		else if (first > last)
		{
			//Make a valid range
			sum_natural_number(last, first);
		}
		else
		{
			//First count  number elements
			int element = (last - first);
			//Formula
			// first *(total_element+1) * ((total_element) * (total_element + 1) / 2)
			long sum = first * (element + 1) + ((element) * (element + 1) / 2);
			//Display calculated result
			System.out.print("Sum of natural numbers from ( " + first + " to " + last + " ) is " + sum + "\n");
		}
	}
	public static void main(String[] args)
	{
		MyMaths obj = new MyMaths();
		//Test case
		obj.sum_natural_number(5, 10);
		obj.sum_natural_number(20, 25);
		obj.sum_natural_number(4, 14);
		obj.sum_natural_number(5, 13);
	}
}

Output

Sum of natural numbers from ( 5 to 10 ) is 45
Sum of natural numbers from ( 20 to 25 ) is 135
Sum of natural numbers from ( 4 to 14 ) is 99
Sum of natural numbers from ( 5 to 13 ) is 81
//Include header file
#include <iostream>

using namespace std;
// C++ Program 
// Sum of natural numbers in given range
class MyMaths
{
	public:
		//Calculating the sum of n natural numbers from two numbers
		void sum_natural_number(int first, int last)
		{
			if (first <= 0 || last <= 0)
			{
				return;
			}
			else if (first > last)
			{
				//Make a valid range
				this->sum_natural_number(last, first);
			}
			else
			{
				//First count  number elements
				int element = (last - first);
				//Formula
				// first *(total_element+1) * ((total_element) * (total_element + 1) / 2)
				long sum = first * (element + 1) + ((element) * (element + 1) / 2);
				//Display calculated result
				cout << "Sum of natural numbers from ( " << first << " to " << last << " ) is " << sum << "\n";
			}
		}
};
int main()
{
	MyMaths obj = MyMaths();
	//Test case
	obj.sum_natural_number(5, 10);
	obj.sum_natural_number(20, 25);
	obj.sum_natural_number(4, 14);
	obj.sum_natural_number(5, 13);
	return 0;
}

Output

Sum of natural numbers from ( 5 to 10 ) is 45
Sum of natural numbers from ( 20 to 25 ) is 135
Sum of natural numbers from ( 4 to 14 ) is 99
Sum of natural numbers from ( 5 to 13 ) is 81
//Include namespace system
using System;
// C# Program 
// Sum of natural numbers in given range
class MyMaths
{
	//Calculating the sum of n natural numbers from two numbers
	public void sum_natural_number(int first, int last)
	{
		if (first <= 0 || last <= 0)
		{
			return;
		}
		else if (first > last)
		{
			//Make a valid range
			sum_natural_number(last, first);
		}
		else
		{
			//First count  number elements
			int element = (last - first);
			//Formula
			// first *(total_element+1) * ((total_element) * (total_element + 1) / 2)
			long sum = first * (element + 1) + ((element) * (element + 1) / 2);
			//Display calculated result
			Console.Write("Sum of natural numbers from ( " + first + " to " + last + " ) is " + sum + "\n");
		}
	}
	public static void Main(String[] args)
	{
		MyMaths obj = new MyMaths();
		//Test case
		obj.sum_natural_number(5, 10);
		obj.sum_natural_number(20, 25);
		obj.sum_natural_number(4, 14);
		obj.sum_natural_number(5, 13);
	}
}

Output

Sum of natural numbers from ( 5 to 10 ) is 45
Sum of natural numbers from ( 20 to 25 ) is 135
Sum of natural numbers from ( 4 to 14 ) is 99
Sum of natural numbers from ( 5 to 13 ) is 81
<?php
// Php Program 
// Sum of natural numbers in given range
class MyMaths
{
	//Calculating the sum of n natural numbers from two numbers
	public	function sum_natural_number($first, $last)
	{
		if ($first <= 0 || $last <= 0)
		{
			return;
		}
		else if ($first > $last)
		{
			//Make a valid range
			$this->sum_natural_number($last, $first);
		}
		else
		{
			//First count  number elements
			$element = ($last - $first);
			//Formula
			// first *(total_element+1) * ((total_element) * (total_element + 1) / 2)
			$sum = $first * ($element + 1) + (intval(($element) * ($element + 1) / 2));
			//Display calculated result
			echo "Sum of natural numbers from ( ". $first ." to ". $last ." ) is ". $sum ."\n";
		}
	}
}

function main()
{
	$obj = new MyMaths();
	//Test case
	$obj->sum_natural_number(5, 10);
	$obj->sum_natural_number(20, 25);
	$obj->sum_natural_number(4, 14);
	$obj->sum_natural_number(5, 13);
}
main();

Output

Sum of natural numbers from ( 5 to 10 ) is 45
Sum of natural numbers from ( 20 to 25 ) is 135
Sum of natural numbers from ( 4 to 14 ) is 99
Sum of natural numbers from ( 5 to 13 ) is 81
// Node Js Program 
// Sum of natural numbers in given range
class MyMaths
{
	//Calculating the sum of n natural numbers from two numbers
	sum_natural_number(first, last)
	{
		if (first <= 0 || last <= 0)
		{
			return;
		}
		else if (first > last)
		{
			//Make a valid range
			this.sum_natural_number(last, first);
		}
		else
		{
			//First count  number elements
			var element = (last - first);
			//Formula
			// first *(total_element+1) * ((total_element) * (total_element + 1) / 2)
			var sum = first * (element + 1) + (parseInt((element) * (element + 1) / 2));
			//Display calculated result
			process.stdout.write("Sum of natural numbers from ( " + first + " to " + last + " ) is " + sum + "\n");
		}
	}
}

function main()
{
	var obj = new MyMaths();
	//Test case
	obj.sum_natural_number(5, 10);
	obj.sum_natural_number(20, 25);
	obj.sum_natural_number(4, 14);
	obj.sum_natural_number(5, 13);
}
main();

Output

Sum of natural numbers from ( 5 to 10 ) is 45
Sum of natural numbers from ( 20 to 25 ) is 135
Sum of natural numbers from ( 4 to 14 ) is 99
Sum of natural numbers from ( 5 to 13 ) is 81
#  Python 3 Program 
#  Sum of natural numbers in given range
class MyMaths :
	# Calculating the sum of n natural numbers from two numbers
	def sum_natural_number(self, first, last) :
		if (first <= 0 or last <= 0) :
			return
		
		elif(first > last) :
			# Make a valid range
			self.sum_natural_number(last, first)
		else :
			# First count  number elements
			element = (last - first)
			# Formula
			#  first *(total_element+1) * ((total_element) * (total_element + 1) / 2)
			sum = first * (element + 1) + (int((element) * (element + 1) / 2))
			# Display calculated result
			print("Sum of natural numbers from ( ", first ," to ", last ," ) is ", sum )
		
	

def main() :
	obj = MyMaths()
	# Test case
	obj.sum_natural_number(5, 10)
	obj.sum_natural_number(20, 25)
	obj.sum_natural_number(4, 14)
	obj.sum_natural_number(5, 13)

if __name__ == "__main__": main()

Output

Sum of natural numbers from (  5  to  10  ) is  45
Sum of natural numbers from (  20  to  25  ) is  135
Sum of natural numbers from (  4  to  14  ) is  99
Sum of natural numbers from (  5  to  13  ) is  81
#  Ruby Program 
#  Sum of natural numbers in given range
class MyMaths

	# Calculating the sum of n natural numbers from two numbers
	def sum_natural_number(first, last)
	
		if (first <= 0 || last <= 0)
			return
		elsif(first > last)
			# Make a valid range
			self.sum_natural_number(last, first)
		else
		
			# First count  number elements
			element = (last - first)
			# Formula
			#  first *(total_element+1) * ((total_element) * (total_element + 1) / 2)
			sum = first * (element + 1) + ((element) * (element + 1) / 2)
			# Display calculated result
			print("Sum of natural numbers from ( ", first ," to ", last ," ) is ", sum ,"\n")
		end
	end
end
def main()

	obj = MyMaths.new()
	# Test case
	obj.sum_natural_number(5, 10)
	obj.sum_natural_number(20, 25)
	obj.sum_natural_number(4, 14)
	obj.sum_natural_number(5, 13)
end
main()

Output

Sum of natural numbers from ( 5 to 10 ) is 45
Sum of natural numbers from ( 20 to 25 ) is 135
Sum of natural numbers from ( 4 to 14 ) is 99
Sum of natural numbers from ( 5 to 13 ) is 81
// Scala Program 
// Sum of natural numbers in given range
class MyMaths
{
	//Calculating the sum of n natural numbers from two numbers
	def sum_natural_number(first: Int, last: Int): Unit = {
		if (first <= 0 || last <= 0)
		{
			return;
		}
		else if (first > last)
		{
			//Make a valid range
			sum_natural_number(last, first);
		}
		else
		{
			//First count  number elements
			var element: Int = (last - first);
			//Formula
			// first *(total_element+1) * ((total_element) * (total_element + 1) / 2)
			var sum: Long = first * (element + 1) + (((element) * (element + 1) / 2).toInt);
			//Display calculated result
			print("Sum of natural numbers from ( " + first + " to " + last + " ) is " + sum + "\n");
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var obj: MyMaths = new MyMaths();
		//Test case
		obj.sum_natural_number(5, 10);
		obj.sum_natural_number(20, 25);
		obj.sum_natural_number(4, 14);
		obj.sum_natural_number(5, 13);
	}
}

Output

Sum of natural numbers from ( 5 to 10 ) is 45
Sum of natural numbers from ( 20 to 25 ) is 135
Sum of natural numbers from ( 4 to 14 ) is 99
Sum of natural numbers from ( 5 to 13 ) is 81
// Swift Program 
// Sum of natural numbers in given range
class MyMaths
{
	//Calculating the sum of n natural numbers from two numbers
	func sum_natural_number(_ first: Int, _ last: Int)
	{
		if (first <= 0 || last <= 0)
		{
			return;
		}
		else if (first > last)
		{
			//Make a valid range
			self.sum_natural_number(last, first);
		}
		else
		{
			//First count  number elements
			let element: Int = (last - first);
			//Formula
			// first *(total_element+1) * ((total_element) * (total_element + 1) / 2)
			let sum: Int = first * (element + 1) + ((element) * (element + 1) / 2);
			//Display calculated result
			print("Sum of natural numbers from ( ", first ," to ", last ," ) is ", sum );
		}
	}
}
func main()
{
	let obj: MyMaths = MyMaths();
	//Test case
	obj.sum_natural_number(5, 10);
	obj.sum_natural_number(20, 25);
	obj.sum_natural_number(4, 14);
	obj.sum_natural_number(5, 13);
}
main();

Output

Sum of natural numbers from (  5  to  10  ) is  45
Sum of natural numbers from (  20  to  25  ) is  135
Sum of natural numbers from (  4  to  14  ) is  99
Sum of natural numbers from (  5  to  13  ) is  81

Time Complexity

The time complexity of this code is constant, O(1), as the calculations performed inside the sum_natural_number function involve only basic arithmetic operations. The execution time remains constant regardless of the input values.

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment