-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
HarshadNumber.cpp
49 lines (41 loc) · 930 Bytes
/
HarshadNumber.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*
A number is said to be a Harshad Number if it is divisible by the sum of its digits.
For example: The number 84 is divisible by the sum (12) of its digits (8, 4).
*/
#include <bits/stdc++.h>
using namespace std;
// Function to check whether the Number is Harshad Number or Not.
bool isHarshad(int number)
{
int sum = 0;
int copy = number;
while (number > 0)
{
int digit = number % 10;
number = number / 10;
sum += digit;
}
return copy % sum == 0;
}
int main()
{
cout << "Enter a Number:" << endl;
int input;
cin >> input;
if (isHarshad(input))
cout << input << " is a Harshad Number." << endl;
else
cout << input << " is not a Harshad Number." << endl;
return 0;
}
/*
Time Complexity: O(log(n))
Space Complexity: O(1)
Sample Input/Output
Enter a Number:
84
84 is a Harshad Number.
Enter a Number:
16
16 is not a Harshad Number.
*/