Check whether a number is Harshad number or not (Niven number) | faceprep

Program to check whether a number is a Harshad number or not (Niven number) is discussed here. Harshad Number is an integer that is divisible by the sum of its digits.

Input format:

  • Input consists of 1 integer.
  • If the given number is Harshad Number display Harshad Number or display Not Harshad Number.

Sample Input:
1729

Sample Output:
Harshad Number

Algorithm to check whether a number is Harshad number or not

  • Input the number.
  • Find the sum of its digits.
  • If the number is divisible by the sum of its digits, print “Harshad Number”.
  • Else, display “Not Harshad Number”.

Program to check whether a number is a Harshad number or not is given below

// C program to check whether a number is a Harshad number or not

#include<stdio.h>
int main()
{
//fill the code
int num;
int temp;
scanf(“%d”,&num);
int sum = 0;
temp = num;
while(temp)
{
sum += temp % 10;
temp = temp / 10;
}
int res = num % sum;
if(res == 0)
printf(“Harshad Number”);
else
printf(“Not Harshad Number”);
return 0;
}

// C++ program to check whether a number is a Harshad number or not

#include<iostream>
using namespace std;

int main()
{
//fill the code
int num;
int temp;
cin >> num;
int sum = 0;
temp = num;
while(temp)
{
sum += temp % 10;
temp = temp / 10;
}
int res = num % sum;
if(res == 0)
cout << “Harshad Number”;
else
cout << “Not Harshad Number”;
return 0;
}

// Java program to check whether a number is a Harshad number or not

import java.util.*;
public class Main
{
public static void main(String[] args)
{
int num, temp;
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
int sum = 0;
temp = num;
while(temp > 0)
{
sum += temp % 10;
temp = temp / 10;
}
int res = num % sum;
if(res == 0)
System.out.print(“Harshad Number”);
else
System.out.print(“Not Harshad Number”);
}
}

# Python program to check whether a number is a Harshad number or not

num = int(input())
sum = 0
temp = num
while(temp > 0):
sum += temp % 10
temp = int(temp / 10)
res = num % sum
if(res == 0):
print(“Harshad Number”);
else:
print(“Not Harshad Number”);

Output:

Harshad number or not