|
1 |
| -// Wikipedia for Harshad Number : https://en.wikipedia.org/wiki/Harshad_number |
2 | 1 | package com.thealgorithms.maths;
|
3 | 2 |
|
4 |
| -import java.util.Scanner; |
| 3 | +// Wikipedia for Harshad Number : https://en.wikipedia.org/wiki/Harshad_number |
5 | 4 |
|
6 | 5 | public class HarshadNumber {
|
7 | 6 |
|
8 |
| - public static void main(String[] args) { |
9 |
| - Scanner sc = new Scanner(System.in); |
10 |
| - System.out.print("Enter a number : "); |
11 |
| - long a = sc.nextLong(); |
| 7 | + /** |
| 8 | + * A function to check if a number is Harshad number or not |
| 9 | + * |
| 10 | + * @param n The number to be checked |
| 11 | + * @return {@code true} if {@code a} is Harshad number, otherwise |
| 12 | + * {@code false} |
| 13 | + */ |
| 14 | + public static boolean isHarshad(long n) { |
| 15 | + if (n <= 0) |
| 16 | + return false; |
| 17 | + |
| 18 | + long t = n; |
| 19 | + int sumOfDigits = 0; |
| 20 | + while (t > 0) { |
| 21 | + sumOfDigits += t % 10; |
| 22 | + t /= 10; |
| 23 | + } |
12 | 24 |
|
13 |
| - checkHarshadNumber(a); |
| 25 | + return n % sumOfDigits == 0; |
14 | 26 | }
|
15 | 27 |
|
16 | 28 | /**
|
17 | 29 | * A function to check if a number is Harshad number or not
|
18 | 30 | *
|
19 |
| - * @param a The number which should be checked |
| 31 | + * @param s The number in String to be checked |
| 32 | + * @return {@code true} if {@code a} is Harshad number, otherwise |
| 33 | + * {@code false} |
20 | 34 | */
|
21 |
| - public static void checkHarshadNumber(long a) { |
22 |
| - long b = a; |
23 |
| - int sum = 0; |
24 |
| - |
25 |
| - // this is just for showing the explanation else it's of no use you can ommit it |
26 |
| - int[] each = new int[Long.toString(a).length()]; |
27 |
| - |
28 |
| - int c = 0; |
29 |
| - |
30 |
| - while (b > 0) { |
31 |
| - sum += b % 10; |
32 |
| - each[c] = (int) (b % 10); |
33 |
| - b /= 10; |
34 |
| - c++; |
| 35 | + public static boolean isHarshad(String s) { |
| 36 | + long n = Long.valueOf(s); |
| 37 | + if (n <= 0) |
| 38 | + return false; |
| 39 | + |
| 40 | + int sumOfDigits = 0; |
| 41 | + for (char ch : s.toCharArray()) { |
| 42 | + sumOfDigits += ch - '0'; |
35 | 43 | }
|
36 | 44 |
|
37 |
| - if (a % sum == 0) { |
38 |
| - System.out.println(a + " is a Harshad Number"); |
39 |
| - |
40 |
| - // For you better explanation how is that a Harshad Number |
41 |
| - System.out.println("\nExplaination :"); |
42 |
| - |
43 |
| - for (int i = each.length - 1; i >= 0; i--) { |
44 |
| - System.out.print(each[i] + " "); |
45 |
| - if (i != 0) { |
46 |
| - System.out.print("+ "); |
47 |
| - } |
48 |
| - } |
49 |
| - |
50 |
| - System.out.println("= " + sum); |
51 |
| - System.out.println(sum + " × " + (a / sum) + " = " + a); |
52 |
| - } else { |
53 |
| - System.out.println(a + " is not a Harshad Number"); |
54 |
| - } |
| 45 | + return n % sumOfDigits == 0; |
55 | 46 | }
|
56 | 47 | }
|
0 commit comments