C++ program to check whether a number is a Harshad Number or not
Harshad Number in C++
A Harshad number is a positive integer that is divisible by the sum of the digits of the integer. It is also called the Niven number.
For Example : 153 Sum of digits = 1 + 5 + 3 = 9 153is divisible by 9 so 153 is a Harshad Number.
Algorithm:-
For input num
- Initialize a variable sum = 0
- Extract each digit of num
- Add each digit to sum variable
- If at the end num is completely divisible by sum
- Then its a harshad’s number
Code in C++
Run
#include <iostream> using namespace std; int checkHarshad(int num){ int sum = 0; int temp = num; while(temp != 0){ sum = sum + temp % 10; temp /= 10; } // will return 1 if num is divisible by sum, else 0 return num % sum == 0; } int main () { int n = 153; if(checkHarshad(n)) cout << n << " is a Harshad's number"; else cout << n << " is not a Harshad's number"; return 0; } // Time complexity: O(N) // Space complexity: O(1) // Where N is the number of digits in number
Output
Enter number: 71 71 is not a harshad number
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
- Positive or Negative number: C | C++ | Java | Python
- Even or Odd number: C | C++ | Java | Python
- Sum of First N Natural numbers: C | C++ | Java | Python
- Sum of N natural numbers: C | C++ | Java | Python
- Sum of numbers in a given range: C | C++ | Java | Python
- Greatest of two numbers: C | C++ | Java | Python
- Greatest of the Three numbers: C | C++ | Java | Python
- Leap year or not: C | C++ | Java | Python
- Prime number: C | C++ | Java | Python
- Prime number within a given range: C | C++ | Java | Python
- Sum of digits of a number: C | C++ | Java | Python
- Reverse of a number : C | C++ | Java | Python
- Palindrome number: C | C++ | Java | Python
- Armstrong number : C | C++ | Java | Python
- Armstrong number in a given range : C | C++ | Java | Python
- Fibonacci Series upto nth term : C | C++ | Java | Python
- Find the Nth Term of the Fibonacci Series : C | C++ | Java | Python
- Factorial of a number : C | C++ | Java | Python
- Power of a number : C | C++ | Java | Python
- Factor of a number : C | C++ | Java | Python
- Strong number : C | C++ | Java | Python
- Perfect number : C | C++ | Java | Python
- Automorphic number : C | C++ | Java | Python
- Harshad number : C | C++ | Java | Python
- Abundant number : C| C++ | Java | Python
- Friendly pair : C | C++ | Java | Python
Login/Signup to comment
#include
using namespace std;
int main()
{
int num;
cout <>num;
int sum = 0;
int temp = num;
while (temp != 0)
{
int digit = num % 10;
sum = sum + digit;
temp = temp / 10;
}
if (num % sum == 0)
{
cout << num << " is harshad number";
}
else
{
cout << num << " is not harshad number";
}
}