Wednesday, April 19, 2023

How to check Perfect number in Java? Example Tutorial

Hello guys, if you are wondering how to check if a given number is a perfect number or not in Java then you have come to the right place. This is one of the interesting coding problem to solve and learn and improve your coding and programming skill. In face, I learned most of my programming by solving these kind of questions. I started with simple ones like factorial, prime number, palindrome, anagram, string permutations before I started solving tree based problems and Dynamic programming problems. These kind of exercise not only give you a chance to get familiar with the programming language constructs like data type, operators, functions, class etc, but also help to build coding sense, which is nothing but your skill to convert your logic into code. 

For example, if you have gone through the Mathematics in your school and college then you may be familiar with what is a Perfect number and even know how to check if a a given number is perfect or not using pen and paper but converting that logic into code requires coding sense. And, that's what you learn and develop by solving these kind of coding problems. 

In number theory, A perfect number is a positive integer that is equal to the sum of its proper positive divisors, that is, the sum of its positive divisors excluding the number itself. Equivalently, a perfect number is a number that is half the sum of all of its positive divisors. 

The first perfect number is 6, because 1, 2, and 3 are its proper positive divisors, and 1 + 2 + 3 = 6. Equivalently, the number 6 is equal to half the sum of all its positive divisors: ( 1 + 2 + 3 + 6 ) / 2 = 6. The next perfect number is 28 = 1 + 2 + 4 + 7 + 14. This is followed by the perfect numbers 496 and 8128.

Now, let's see how can we write a program to check if a given number is perfect or not in Java. 




How to check if a Given Number is a Perfect number in Java?

In order to check if a given number is perfect or not, you need to find the divisors of that number and once you have found that you need to add them and check if the number is equal to half the sum of all its positive divisors or not. If it is then given number is a perfect number or if not, then its not a perfect number. 

In this program, I have add code to accept input from user using command prompt, this makes the problem bit more interactive as you can run the program and check any number whether its perfect or not. 

How to check Perfect number in Java? Example Tutorial


By the way, logic for checking if a number is perfect or not is contained in isPerfect( int number) method so that you can easily unit test it as well. I have not given any JUnit test in this program but you can write a couple of test to check if the method is behaving as expected or not. Let me know if you stuck, I can also share unit tests for this program. 


import java.util.Scanner;
import java.util.concurrent.TimeUnit;

/**
 * A Java Program to check if a given number is perfect number or not. It returns true if
*  number is perfect, false otherwise.

 * @author JavinPaul
 */
public class Testing {

    public static void main(String args[]) {
        try (Scanner sc = new Scanner(System.in)) {
            int number = Integer.MAX_VALUE;
            while (number != 0) {
                System.out.println("Enter a number to check if it's perfect or not");

                number = sc.nextInt();

               boolean result = isPerfect(number);

                if (result) {
                    System.out.printf("%d is a perfect number %n", number);
                } else {
                    System.out.printf("%d is not a perfect number %n", number);
                }
            }
        }
    }

    public static boolean isPerfect(int number) {
        int sumOfDivisors = 0;
        int copyOfInput = number;

        for (int i = 1; i <= copyOfInput / 2; i++) {
            if (copyOfInput % i == 0) {
                sumOfDivisors += i;
            }
        }

        return number == sumOfDivisors;
    }

}



Output
Enter a number to check if it's perfect or not
6
6 is a perfect number
Enter a number to check if it's perfect or not
28
28 is a perfect number
Enter a number to check if it's perfect or not
19
19 is not a perfect number
Enter a number to check if it's perfect or not



That's all about how to check if a given number is a perfect number in Java or not. This is a nice exercise to build your coding skill as well as to prepare for coding interviews. As I told you earlier, I learned most of my coding by solving this kind of questions. First starting with simple ones like palindrome, factorial, Fibonacci, anagram, and permutations and then slowly moving to solve binary tree based and dynamic programming questions and you can do the same. 

If you get stuck then you can also watch YouTube videos where people share how they solve this problem live or join a coding interview course where they also explains and share tips and tricks to solve these kind of coding problems. Anyway, whatever path you choose, you are bound to benefit as long as you keep solving coding problems. 

Other Resources for Coding Interviews:
Thanks for reading this article so far. If you like this kind of coding and Programming problems for interviews then please share them with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are new to world of coding and data structure and algorithms and looking for some Free Algorithms courses to improve your understanding of Data Structure and Algorithms, then you should also check this list of Free Data Structure and Algorithms Courses for Programmers.

No comments :

Post a Comment