Skip to content

Commit 9c7c538

Browse files
Add check if a number is harshad Number or not (TheAlgorithms#2514)
1 parent f336c40 commit 9c7c538

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Maths/HarshadNumber.java

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

0 commit comments

Comments
 (0)