Harshad (Niven) Number

easy Number Problems

Problem

A Harshad number is divisible by the sum of its digits. Example: 18 has the digit sum 9, and 18 is divisible by 9. Read an integer and print true if it is a Harshad number, otherwise false. Numbers smaller than 1 are not Harshad numbers.

Constraints

  • -10^15 <= n <= 10^15

Examples

Input

18

Output

true

Input

19

Output

false

Solutions

Best approachTime O(d)Space O(1)

We compute the digit sum and check if the number is divisible by it. For positive numbers the digit sum is never 0, so the division is safe.

Same code works in Java810172125Basic features only, so nothing changes between versions.
/*
 * Problem : Check if a number is a Harshad number.
 * Input   : One integer.
 * Output  : true or false.
 * Approach: Divide the number by its digit sum.
 * Time    : O(d)
 * Space   : O(1)
 * Java    : 8 or newer.
 */
import java.util.Scanner;

public class Main {
    // This method receives a number and returns true if the number is a Harshad number.
    static boolean isHarshad(long number) {
        // Step 1: Only positive numbers are checked. This also avoids division by zero later.
        if (number < 1) {
            return false;
        }

        // Step 2: Add the digits. The sum starts at 0.
        long digitSum = 0;
        long remaining = number;
        while (remaining > 0) {
            // Step 2a: Take the last digit and add it. Example: 18 % 10 = 8.
            digitSum = digitSum + remaining % 10;

            // Step 2b: Remove the last digit. Example: 18 / 10 = 1.
            remaining = remaining / 10;
        }

        // Step 3: The number is a Harshad number if it divides by the digit sum without remainder.
        return number % digitSum == 0;
    }

    public static void main(String[] args) {
        long number = new Scanner(System.in).nextLong();
        System.out.println(isHarshad(number));
    }
}
Hints (2)
  1. Which operator gives the last digit?
  2. Which operation removes the last digit?