Home Linux Shell Script to check a number is perfect number or not

Shell Script to check a number is perfect number or not

by Anup Maurya
1 minutes read

In this tutorial, you’ll learn what is a perfect number and also create Shell Script to check a number is perfect number or not.

What is a perfect number?

A number whose sum of factors (excluding the number itself) is equal to the number is called a perfect number. In other words, if the sum of positive divisors (excluding the number itself) of a number equals the number itself is called a perfect number.

For example: 6 is Perfect Number since divisor of 6 are 1, 2 and 3. Sum of its divisor is

1 + 2+ 3 =6

and 28 is also a Perfect Number

since 1+ 2 + 4 + 7 + 14= 28

Other perfect numbers: 496, 8128

Shell Script to check a number is perfect number or not

#!/bin/bash
read -p "Enter a number " num
sum=0
for ((i=1;i<num;i++))
do
if((num%i==0))
then
((sum=sum+i))
fi
done
if((sum==num))
then
 echo "$num is a perfect number"
else
 echo "$num is not a perfect number"
fi

Output

anupmaurya@linux:~$ ./perfectnumber.sh
Enter a number 28
28 is a perfect number
anupmaurya@linux:~$ 

Thank you for reading, If you have reached so far, please like the article, It will encourage me to write more such articles. Do share your valuable suggestions, I appreciate your honest feedback!

related posts

Leave a Comment

Enable Notifications OK No thanks