Q4.Write a code to find perfect number
Perfect Number :- Perfect number, a positive integer equal to the sum of its proper divisors. The smallest Perfect number is 6, which is the sum of 1, 2 and 3.
For Example:-
Input = 28
Output = 28 is the Perfect Number.
So as we can see that the divisor of 28 is 1, 2, 4, 7, 14, so the sum of all the divisors is 28 (1 + 2 + 4 + 7 + 14 = 28). Therefore, 28 is the Perfect number.
Algorithm for Perfect Number
START
Step 1 – Input the number.
Step 2 – Find all divisors of the number except the number itself.
Step 3 – If the sum of all divisors of the number is equal to the number, then return true. Else, return false.
STOP
Code for Perfect Number
#include <stdio.h>
int main()
{
int num=28,i;
int sum;
sum=0;
for(i=1; i< num;i++)
{
if(num%i==0)
sum+=i;
}
if(sum==num)
printf(“%d is a perfect number.”,num);
else
printf(“%d is not a perfect number.”,num);
return 0;
}
#include <bits/stdc++.h>
using namespace std;
int main(){
int num=28,i=1,sum=0;
while(i< num){
if(num%i==0)
sum=sum+i;
i++;
}
if(sum==num)
cout << i << ” is a perfect number\n”;
else
cout << i << ” is not a perfect number\n”;
return 0;
}
public class LFC {
public static void main(String[] args) {
int i, num=28, Sum = 0 ;
for(i = 1 ; i < num ; i++) {
if(num % i == 0) {
Sum = Sum + i;
}
}
if (Sum == num) {
System.out.format(“% d is a Perfect Number”, num);
}
else {
System.out.format(“% d is NOT a Perfect Number”, num);
}
}
}
# Python Program to find Perfect Number using For loop
num = 28
Sum = 0
for i in range(1, num):
if(num % i == 0):
Sum = Sum + i
if (Sum == num):
print(” %d is a Perfect Number” %num)
else:
print(” %d is not a Perfect Number” %num)
function check_perfectnumber($num)
{
// To store the sum
$sum = 0;
// Traversing through each number
// In the range [1,N)
for ($i = 1; $i < $num; $i++)
{
if ($num % $i == 0)
{
$sum = $sum + $i;
}
}
// returns True is sum is equal
// to the original number.
return $sum == $num;
}
// Driver’s code
$num = 28;
if (check_perfectnumber($num))
echo “$num is a Perfect Number”;
else
echo “$num is not a Perfect Number”;
Output
28 is a perfect number.
Recommended Programs
Program to find factorial of a number
Program to count number of digits in a number