Posted on by Kalkicode
Code Mathematics

Find perfect numbers in a given range

The problem at hand involves finding perfect numbers within a given range. A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). For instance, 6 is a perfect number because its divisors are 1, 2, and 3, and 1 + 2 + 3 = 6.

Problem Statement

Given a range of numbers from x to y, the objective is to identify and display all the perfect numbers within this range.

Example

Let's take an example to illustrate the problem:

Example

  • Given range: x = 1, y = 200
  • We need to identify and display the perfect numbers within this range.

Idea to Solve

  1. Loop through the range from x to y.
  2. For each number in the range, calculate its sum of proper divisors.
  3. If the sum of proper divisors equals the number itself, it is a perfect number.

Pseudocode

function isPerfectNumber(num):
    if num < 0:
        return false
    sumOfDivisors = 0
    for i in range(1, num):
        if num % i == 0:
            sumOfDivisors += i
    if sumOfDivisors == num:
        return true
    else:
        return false

function findPerfectNumbersInRange(x, y):
    result = []
    for num in range(x, y + 1):
        if isPerfectNumber(num):
            result.append(num)
    return result

# Example usage
x = 1
y = 200
perfectNumbers = findPerfectNumbersInRange(x, y)
print(perfectNumbers)

Algorithm Explanation

  1. The isPerfectNumber function checks whether a given number is perfect or not.
  2. It iterates through all the numbers from 1 to num - 1, calculating the sum of proper divisors.
  3. If the sum of proper divisors equals the number itself, the function returns true (indicating a perfect number).
  4. The findPerfectNumbersInRange function iterates through the range from x to y, checking each number using the isPerfectNumber function.
  5. If a perfect number is found, it's added to the result list.
  6. Finally, the result list is returned, containing all perfect numbers within the specified range.

Code Solution

/*
    Java program for
    Find perfect numbers in a given range
*/
public class PerfectNumber
{
	// Check given number is perfect or not
	public boolean isPerfectNo(int n)
	{
		if (n < 0)
		{
			return false;
		}
		int sum = 0;
		for (int i = (n / 2); i >= 1; i--)
		{
			if (n % i == 0)
			{
				sum += i;
			}
		}
		if (sum == n)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	public void findPerfectNo(int x, int y)
	{
		// Result indicator
		// Initial false
		boolean result = false;
		System.out.print(" Perfect number in range of (" + 
                         x + "," + y + ") is \n");
		for (int i = x; i <= y; ++i)
		{
			if (isPerfectNo(i))
			{
				// When number is perfect number
				System.out.print("  " + i);
				// Change result status
				result = true;
			}
		}
		if (result == false)
		{
			System.out.print("\n None \n");
		}
	}
	public static void main(String[] args)
	{
		PerfectNumber task = new PerfectNumber();
		// Test A
		int x = 1;
		int y = 200;
		task.findPerfectNo(x, y);
	}
}

Output

 Perfect number in range of (1,200) is
  6  28
// Include header file
#include <iostream>
using namespace std;
/*
    C++ program for
    Find perfect numbers in a given range
*/
class PerfectNumber
{
	public:
		// Check given number is perfect or not
		bool isPerfectNo(int n)
		{
			if (n < 0)
			{
				return false;
			}
			int sum = 0;
			for (int i = (n / 2); i >= 1; i--)
			{
				if (n % i == 0)
				{
					sum += i;
				}
			}
			if (sum == n)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
	void findPerfectNo(int x, int y)
	{
		// Result indicator
		// Initial false
		bool result = false;
		cout << " Perfect number in range of (" 
      		 << x << "," << y << ") is \n";
		for (int i = x; i <= y; ++i)
		{
			if (this->isPerfectNo(i))
			{
				// When number is perfect number
				cout << "  " << i;
				// Change result status
				result = true;
			}
		}
		if (result == false)
		{
			cout << "\n None \n";
		}
	}
};
int main()
{
	PerfectNumber *task = new PerfectNumber();
	// Test A
	int x = 1;
	int y = 200;
	task->findPerfectNo(x, y);
	return 0;
}

Output

 Perfect number in range of (1,200) is
  6  28
// Include namespace system
using System;
/*
    Csharp program for
    Find perfect numbers in a given range
*/
public class PerfectNumber
{
	// Check given number is perfect or not
	public Boolean isPerfectNo(int n)
	{
		if (n < 0)
		{
			return false;
		}
		int sum = 0;
		for (int i = (n / 2); i >= 1; i--)
		{
			if (n % i == 0)
			{
				sum += i;
			}
		}
		if (sum == n)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	public void findPerfectNo(int x, int y)
	{
		// Result indicator
		// Initial false
		Boolean result = false;
		Console.Write(" Perfect number in range of (" + 
                      x + "," + y + ") is \n");
		for (int i = x; i <= y; ++i)
		{
			if (this.isPerfectNo(i))
			{
				// When number is perfect number
				Console.Write("  " + i);
				// Change result status
				result = true;
			}
		}
		if (result == false)
		{
			Console.Write("\n None \n");
		}
	}
	public static void Main(String[] args)
	{
		PerfectNumber task = new PerfectNumber();
		// Test A
		int x = 1;
		int y = 200;
		task.findPerfectNo(x, y);
	}
}

Output

 Perfect number in range of (1,200) is
  6  28
package main
import "fmt"
/*
    Go program for
    Find perfect numbers in a given range
*/

// Check given number is perfect or not
func isPerfectNo(n int) bool {
	if n < 0 {
		return false
	}
	var sum int = 0
	for i :=(n / 2) ; i >= 1 ; i-- {
		if n % i == 0 {
			sum += i
		}
	}
	if sum == n {
		return true
	} else {
		return false
	}
}
func findPerfectNo(x, y int) {
	// Result indicator
	// Initial false
	var result bool = false
	fmt.Print(" Perfect number in range of (", 
		x, ",", y, ") is \n")
	for i := x ; i <= y ; i++ {
		if isPerfectNo(i) {
			// When number is perfect number
			fmt.Print("  ", i)
			// Change result status
			result = true
		}
	}
	if result == false {
		fmt.Print("\n None \n")
	}
}
func main() {
	// Test A
	var x int = 1
	var y int = 200
	findPerfectNo(x, y)
}

Output

 Perfect number in range of (1,200) is
  6  28
<?php
/*
    Php program for
    Find perfect numbers in a given range
*/
class PerfectNumber
{
	// Check given number is perfect or not
	public	function isPerfectNo($n)
	{
		if ($n < 0)
		{
			return false;
		}
		$sum = 0;
		for ($i = ((int)($n / 2)); $i >= 1; $i--)
		{
			if ($n % $i == 0)
			{
				$sum += $i;
			}
		}
		if ($sum == $n)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	public	function findPerfectNo($x, $y)
	{
		// Result indicator
		// Initial false
		$result = false;
		echo(" Perfect number in range of (".$x.
			",".$y.
			") is \n");
		for ($i = $x; $i <= $y; ++$i)
		{
			if ($this->isPerfectNo($i))
			{
				// When number is perfect number
				echo("  ".$i);
				// Change result status
				$result = true;
			}
		}
		if ($result == false)
		{
			echo("\n None \n");
		}
	}
}

function main()
{
	$task = new PerfectNumber();
	// Test A
	$x = 1;
	$y = 200;
	$task->findPerfectNo($x, $y);
}
main();

Output

 Perfect number in range of (1,200) is
  6  28
/*
    Node JS program for
    Find perfect numbers in a given range
*/
class PerfectNumber
{
	// Check given number is perfect or not
	isPerfectNo(n)
	{
		if (n < 0)
		{
			return false;
		}
		var sum = 0;
		for (var i = (parseInt(n / 2)); i >= 1; i--)
		{
			if (n % i == 0)
			{
				sum += i;
			}
		}
		if (sum == n)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	findPerfectNo(x, y)
	{
		// Result indicator
		// Initial false
		var result = false;
		process.stdout.write(" Perfect number in range of (" + 
                             x + "," + y + ") is \n");
		for (var i = x; i <= y; ++i)
		{
			if (this.isPerfectNo(i))
			{
				// When number is perfect number
				process.stdout.write("  " + i);
				// Change result status
				result = true;
			}
		}
		if (result == false)
		{
			process.stdout.write("\n None \n");
		}
	}
}

function main()
{
	var task = new PerfectNumber();
	// Test A
	var x = 1;
	var y = 200;
	task.findPerfectNo(x, y);
}
main();

Output

 Perfect number in range of (1,200) is
  6  28
#    Python 3 program for
#    Find perfect numbers in a given range
class PerfectNumber :
	#  Check given number is perfect or not
	def isPerfectNo(self, n) :
		if (n < 0) :
			return False
		
		sum = 0
		i = (int(n / 2))
		while (i >= 1) :
			if (n % i == 0) :
				sum += i
			
			i -= 1
		
		if (sum == n) :
			return True
		else :
			return False
		
	
	def findPerfectNo(self, x, y) :
		#  Result indicator
		#  Initial false
		result = False
		print(" Perfect number in range of (", x ,",", y ,") is ")
		i = x
		while (i <= y) :
			if (self.isPerfectNo(i)) :
				#  When number is perfect number
				print("  ", i, end = "")
				#  Change result status
				result = True
			
			i += 1
		
		if (result == False) :
			print("\n None ")
		
	

def main() :
	task = PerfectNumber()
	#  Test A
	x = 1
	y = 200
	task.findPerfectNo(x, y)

if __name__ == "__main__": main()

Output

 Perfect number in range of ( 1 , 200 ) is
   6   28
#    Ruby program for
#    Find perfect numbers in a given range
class PerfectNumber 
	#  Check given number is perfect or not
	def isPerfectNo(n) 
		if (n < 0) 
			return false
		end

		sum = 0
		i = (n / 2)
		while (i >= 1) 
			if (n % i == 0) 
				sum += i
			end

			i -= 1
		end

		if (sum == n) 
			return true
		else
 
			return false
		end

	end

	def findPerfectNo(x, y) 
		#  Result indicator
		#  Initial false
		result = false
		print(" Perfect number in range of (", 
              x ,",", y ,") is \n")
		i = x
		while (i <= y) 
			if (self.isPerfectNo(i)) 
				#  When number is perfect number
				print("  ", i)
				#  Change result status
				result = true
			end

			i += 1
		end

		if (result == false) 
			print("\n None \n")
		end

	end

end

def main() 
	task = PerfectNumber.new()
	#  Test A
	x = 1
	y = 200
	task.findPerfectNo(x, y)
end

main()

Output

 Perfect number in range of (1,200) is 
  6  28
/*
    Scala program for
    Find perfect numbers in a given range
*/
class PerfectNumber()
{
	// Check given number is perfect or not
	def isPerfectNo(n: Int): Boolean = {
		if (n < 0)
		{
			return false;
		}
		var sum: Int = 0;
		var i: Int = (n / 2);
		while (i >= 1)
		{
			if (n % i == 0)
			{
				sum += i;
			}
			i -= 1;
		}
		if (sum == n)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	def findPerfectNo(x: Int, y: Int): Unit = {
		// Result indicator
		// Initial false
		var result: Boolean = false;
		print(" Perfect number in range of (" + 
      	x + "," + y + ") is \n");
		var i: Int = x;
		while (i <= y)
		{
			if (isPerfectNo(i))
			{
				// When number is perfect number
				print("  " + i);
				// Change result status
				result = true;
			}
			i += 1;
		}
		if (result == false)
		{
			print("\n None \n");
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var task: PerfectNumber = new PerfectNumber();
		// Test A
		var x: Int = 1;
		var y: Int = 200;
		task.findPerfectNo(x, y);
	}
}

Output

 Perfect number in range of (1,200) is
  6  28
/*
    Swift 4 program for
    Find perfect numbers in a given range
*/
class PerfectNumber
{
	// Check given number is perfect or not
	func isPerfectNo(_ n: Int) -> Bool
	{
		if (n < 0)
		{
			return false;
		}
		var sum: Int = 0;
		var i: Int = (n / 2);
		while (i >= 1)
		{
			if (n % i == 0)
			{
				sum += i;
			}
			i -= 1;
		}
		if (sum == n)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	func findPerfectNo(_ x: Int, _ y: Int)
	{
		// Result indicator
		// Initial false
		var result: Bool = false;
		print(" Perfect number in range of (", 
              x ,",", y ,") is ");
		var i: Int = x;
		while (i <= y)
		{
			if (self.isPerfectNo(i))
			{
				// When number is perfect number
				print("  ", i, terminator: "");
				// Change result status
				result = true;
			}
			i += 1;
		}
		if (result == false)
		{
			print("\n None ");
		}
	}
}
func main()
{
	let task: PerfectNumber = PerfectNumber();
	// Test A
	let x: Int = 1;
	let y: Int = 200;
	task.findPerfectNo(x, y);
}
main();

Output

 Perfect number in range of ( 1 , 200 ) is
   6   28
/*
    Kotlin program for
    Find perfect numbers in a given range
*/
class PerfectNumber
{
	// Check given number is perfect or not
	fun isPerfectNo(n: Int): Boolean
	{
		if (n < 0)
		{
			return false;
		}
		var sum: Int = 0;
		var i: Int = (n / 2);
		while (i >= 1)
		{
			if (n % i == 0)
			{
				sum += i;
			}
			i -= 1;
		}
		if (sum == n)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	fun findPerfectNo(x: Int, y: Int): Unit
	{
		// Result indicator
		// Initial false
		var result: Boolean = false;
		print(" Perfect number in range of (" + 
              x + "," + y + ") is \n");
		var i: Int = x;
		while (i <= y)
		{
			if (this.isPerfectNo(i))
			{
				// When number is perfect number
				print("  " + i);
				// Change result status
				result = true;
			}
			i += 1;
		}
		if (result == false)
		{
			print("\n None \n");
		}
	}
}
fun main(args: Array < String > ): Unit
{
	val task: PerfectNumber = PerfectNumber();
	// Test A
	val x: Int = 1;
	val y: Int = 200;
	task.findPerfectNo(x, y);
}

Output

 Perfect number in range of (1,200) is
  6  28

Time Complexity

  • For each number in the range, the isPerfectNumber function takes O(num) time.
  • Since we're iterating through the range of (y - x + 1) numbers, the overall time complexity is O((y - x + 1) * num).

The time complexity can be improved by employing more advanced techniques, but this simple approach is acceptable for most practical cases.

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