Check whether a given number is a perfect number or not

Description

Perfect number is a number which is equal to sum of its divisor.
Ex:  6,28,496,8128

C/C++

/* C Program to check Perfect Number*/
//Save it as PerfectNumber.c

#include<stdio.h>
int main(){

    int i, num, sum=0;

    printf("Enter a number : ");
    scanf("%d",&num);

    /*Finding divisor and adding them*/
    for(i=1;i<=(num-1);i++){
        if(num%i == 0){
            sum += i;
        }
    }

    //Checking sum of divisor is equal to number or not
    if(sum == num){
        printf("%d is a perfect number",num);
    }else{
        printf("%d is not a perfect number",num);
    }

    return 0;
}
Input:
Enter a number : 496

Output:
496 is a perfect number

Java

/* Java Program to check Perfect Number*/
//Save it as PerfectNumber.java

import java.io.*;
import java.util.Scanner;

public class PerfectNumber {

    public static void main(String[] args) {

            Scanner scanner = new Scanner(System.in);
        
            int i, num, sum=0;

        System.out.println("Enter a number : ");
        num  = scanner.nextInt();

            //Finding divisor and adding them
        for(i=1;i<=(num-1);i++){
            if(num%i == 0){
                sum += i;
            }
        }

            //Checking sum of divisor is equal to number or not
        if(sum == num){
            System.out.println(num + " is a perfect number");
        }else{
        	System.out.println(num + " is a not perfect number");
        }
    }
}
Input:
Enter a number : 
496

Output:
496 is a perfect number

Related programs

1) Program to Check Whether a Number is Prime or Not
2) Program to Check Whether a Character is a Vowel or Not
3) Program to Check Whether a Number is Even or Odd
4) Program To Check Armstrong Number
5) Program to Check Leap Year
6) Program to calculate Volume and Surface Area of Sphere
7) Program to add two complex numbers
8) Program to find HCF using Recursion
9) Program to calculate square root of a number without using standard library function sqrt()
10) Program to find HCF(Highest Common Factor)/GCD(Greatest Common Divisor) and LCM(Least Common Multiple)
Share Me

Leave a Reply