
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If a Number is Harshad Number in C++
A Harshad number is a special type of number. A Harshad number or Niven number is a number that is completely divisible by the sum of its digits without leaving any remainder. In this article, we are going to learn how we can check whether a given number is a Harshad number or not.
Problem Description
We are given a number and we have to return true if the given number is Harshad or Niven number and false if the given number is not a Harshad number.
Example 1
Input:
108
Output:
yes
Explanation:
The sum of digits: 1 + 0 + 8 = 9
Now, we divide: 108 ÷ 9 = 12
It is completely divisible and leaves no remainder.
So, this is a Harshad number.
Example 2
Input:
13
Output:
no
Explanation:
The sum of digits of 13 = 1 + 3 = 4.
When 13 is divided by 4, it leaves a remainder of 1.
So, this is not a Harshad number.
Checking a Harshad Number in C++
In C++, to check whether a given number is Harshad or not, we will use a simple and straightforward approach. We will take a variable to store the sum of the digits of the number. Now, we check if the number is divisible by the sum of digits or not. If the sum is completely divisible by the number, then print "yes, this is a Harshad number", else print "no, this is not a Harshad number".
C++ Program to Check Harshad Number
#include <bits/stdc++.h> using namespace std; int main() { int number = 108; int temp = number; int sum = 0; while (temp != 0) { sum += temp % 10; temp /= 10; } if (number % sum == 0) { cout << "yes, this is a Harshad number" << "\n"; } else { cout << "no, this is not a Harshad number" << "\n"; } return 0; }
Output
yes, this is a Harshad number
Time and Space Complexity
Time Complexity: O(n), as we are finding the sum of the digits.
Space Complexity: O(1), constant space.