Problem Statement: Check if the number is a Harshad(or Niven) number or not.
Examples:
Example 1: Input: 378 Output: Yes it is a Harshad number. Explanation: 3+7+8=18. 378 is divisible by 18. Therefore 378 is a harshad number. Example 2: Input: 379 Output: No it is not a Harshad number. Explanation: 3+7+9=19. 379 is not divisible by 19. Therefore 379 is a harshad number.
Solution
Disclaimer: Don’t jump directly to the solution, try it out yourself first.
Solution 1:
Intuition: If the sum of digits is divisible by the number then it is called Harshad number.
Approach:
- Maintain a variable sum to store sum of digits of the number.
- Now check if n is divisible by sum or not.
- If it is divisible print yes,else print no.
Code:
C++ Code
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n = 378;
int temp = n;
int sum = 0;
while (temp!=0) {
sum += temp % 10;
temp /= 10;
}
if (n % sum == 0) {
cout << "YES it is Harshad Number" << "\n";
}
else {
cout << "NO it is not Harshad Number" << "\n";
}
}
Output:
YES it is Harshad Number
Time Complexity: O(N), where N is the number of digits
Space Complexity: O(1).
Java Code
public class Main {
public static void main(String args[]) {
int n = 378;
int temp = n;
int sum = 0;
while (temp != 0) {
sum += temp % 10;
temp /= 10;
}
if (n % sum == 0) {
System.out.println("YES it is Harshad Number");
} else {
System.out.println("NO it is Harshad Number");
}
}
}
Output:
YES it is Harshad Number
Time Complexity: O(N), where N is the number of digits
Space Complexity: O(1).
Solution 2: Using string
Intuition: In solution1 we needed an extra variable temp to store the value of n, but if we use string there won’t be any need for the extra variable.
Approach:
- Convert the intger to string.
- Traverse through the string and calculate the sum of all the digits.
- Now check if the number is divisible by the sum of digits or not.
- If the number is divisible, print yes, else print no.
Code:
C++ Code
#include<bits/stdc++.h>
using namespace std;
int main()
{
int num=378;
string s = to_string(num);
int sum = 0;
for (int i = 0; i < s.length(); i++) {
sum += s[i] - '0';
}
if (num % sum == 0) {
cout << "YES it is Harshad Number" << "\n";
}
else {
cout << "NO it is not a Harshad Number" << "\n";
}
}
Output:
YES it is Harshad Number
Time Complexity: O(N), where N is the number of digits
Space Complexity: O(1).
Java Code
public class Main {
public static void main(String args[]) {
int num=378;
String s = Integer.toString(num);
int sum = 0;
for (int i = 0; i < s.length(); i++) {
sum += s.charAt(i) - '0';
}
if (num % sum == 0) {
System.out.print("YES it is a Harshad Number");
} else {
System.out.print("NO it is Not a Harshad Number");
}
}
}
Output:
YES it is Harshad Number
Time Complexity: O(N), where N is the number of digits
Space Complexity: O(1).
Special thanks to Pranav Padawe for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article