Program to Check if a Number is a Harshad Number in C++
Harshad Number
A Harshad number (also called a Niven number) is a number that is divisible by the sum of its digits. For example, 18 is a Harshad number because 1 + 8 = 9 and 18 is divisible by 9.
We will explore a method to check if a given number is a Harshad number using C++ programming.
Method: Using a while Loop
We extract each digit, sum them up, and check if the original number is divisible by this sum.
#include <iostream>
using namespace std;
bool isHarshad(int num) {
int originalNum = num, sum = 0, digit;
// Calculate the sum of digits
while (num > 0) {
digit = num % 10;
sum += digit;
num /= 10;
}
return (originalNum % sum == 0);
}
int main() {
int num;
cout << "Enter a number: ";
cin >> num;
if (isHarshad(num))
cout << num << " is a Harshad number";
else
cout << num << " is not a Harshad number";
return 0;
}
Output:
Enter a number: 18 18 is a Harshad number