Untitled

 avatar
unknown
plain_text
10 months ago
1.4 kB
16
Indexable
package LogicalProblems;

import java.util.Scanner;

public class Harshad {

    /**
     *This class Takes a positive integer N, determine whether it is a Harshad number (also known as a Niven number) or not.
     * A number is said to be a Harshad number if it is divisible by the sum of its digits.
     *
     * Examples:
     * Input: 378
     * Output: true
     * Explanation:
     * Sum of digits = 3 + 7 + 8 = 18
     * 378 is divisible by 18 → 378 % 18 == 0
     * So, it is a Harshad number.
     *
     * Input: 379
     * Output: false
     * Explanation:
     * Sum of digits = 3 + 7 + 9 = 19
     * 379 is not divisible by 19 → 379 % 19 != 0
     * So, it is not a Harshad number.
     */
    public static boolean checkHarshad(int n){

        int num = n;
        int sum = 0;
        boolean bool = false;

        while (n > 0) {
            sum = sum + n % 10;
            n = n / 10;
        }
        if (num % sum == 0) {
           bool =  true;
        }
        return bool;
    }

    public static void main(String[] args) {

        Scanner s = new Scanner(System.in);
        System.out.print("Enter a Number -> ");
        int num = s.nextInt();

        if (checkHarshad(num)) {
            System.out.println( num + " is Harshad");
        } else {
            System.out.println(num + " is Not Harshad");
        }
    }
}
Editor is loading...
Leave a Comment