Java Program to Check Hamming Number

In the previous article, we have discussed Java Program to Check Mersenne Number

In this article we are going to understand what Hamming number is and how we can check whether a number is Hamming or not in Java with examples.

Program to Check Hamming Number

Hamming numbers are numbers whose prime factors are 2, 3 or 5 only.

Example :

  • 9: Prime Factors= 3*3 Hamming number
  • 20: Prime Factors= 2*2*5 Hamming number
  • 14: Prime Factors= 2*7 Not Hamming number

In the above examples the number 9 and 20 are Hamming numbers as they have no other prime factors than 2, 3 or 5. However 14 is not a Hamming number.

Interested in programming and want to excel in it by choosing the short ways. Then, practicing with the available Java Program list is mandatory.

Approach :

  1. We ask the user to enter or declare a number and store it .
  2. We find all the prime factors of the number.
  3. If there is no other prime factor than 2,3 or 5 then the number is said to be Hamming number.

Program:

import java.util.Scanner;

public class HammingNumber
{
    public static void main(String args[])
    {
        //Taking the number as input from the user using scanner class
        Scanner scan = new Scanner(System.in);
        System.out.print("Enter a number : ");
        int num = scan.nextInt();

        boolean flag = true;
        for(int i = 2; i<=num; i++)
        {
            // Only checks for numbers except 2,3 and 5
            if(i!=2&&i!=3&&i!=5)
                // Checks if there are some other prime factors
                if(num%i==0&&isPrime(i))
                {
                    // Sets the flag to false if there are some other prime factors
                    flag = false;
                    break;
                }
        }

        if(flag)
        {
            System.out.println(num+" is a Hamming number");
        }
        else
        {
            System.out.println(num+" is Not a Hamming number");
        }
    }

    // Function that checks for prime
    static boolean isPrime(int num)
    {
        boolean flag = true;
        for(int i = 2; i<=num/2; i++)
        {
            if(num%i==0)
            {
                flag = false;
                break;
            }
        }
        return flag;
    }
}
Output:

Case-1

Enter a number : 20
20 is a Hamming number

Case-2

Enter a number : 21
21 is a Hamming number

Provided list of Simple Java Programs is specially designed for freshers and beginners to get familiarize with the concepts of Java programming language and become pro in coding

Related Java Programs: