Program opened below. You can scroll through the algorithm, Java code and output.

Hamming Number

Download .java

Question

A Hamming number is a positive integer whose prime factors are only 2, 3 and 5. Accept N and determine whether it is a Hamming number.

Step 1: Start. Step 2: Declare the variables and data structures required for the task. Step 3: Input N and validate N > 0. Step 4: Set temp=N. Step 5: Initialize the counters, flags, accumulators or result structures needed by the solution. Step 6: While temp is divisible by 2, divide temp by 2. Step 7: Repeat for 3 and 5. Step 8: If temp becomes 1, all prime factors were 2, 3 or 5. Step 9: Store the computed result and prepare it for display. Step 10: Display the result and stop. Step 11: Stop.
Java
import java.util.*;
class HammingNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        if (n < 1) {
            System.out.println("INVALID INPUT");
            return;
        }
    int x = n;
    for (int p : new int[]{2, 3, 5}) {
        while (x % p == 0) {
            x /= p;
        }
}
System.out.println(x == 1 ? "HAMMING NUMBER" : "NOT A HAMMING NUMBER");
}
}
Input: 6 Output: HAMMING NUMBER
← Previous Program 76 of 84 Next →

Share a comment or request a program

Use this form to send a comment, report an issue, or suggest a new practical. Your message will be saved for review by the school.