Check whether a number is Harshad number or not

Select Articles

Check whether a number is Harshad number or not

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

Get the input from the user

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

C

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

#include

int main()

{

    //fill the code

    int num;

    int temp;

    scanf(“%d”,#);

    int sum = 0;

    temp = num;

    while(temp)

    {

        sum += temp ;

        temp = temp / 10;

    }

    int res = num % sum;

    if(res == 0)

        printf(“Harshad Number”);

    else

        printf(“Not Harshad Number”);

    return 0;

}

 

C++

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

#include

using namespace std;

int main()

{

//fill the code

    int num;

    int temp;

    cin >> num;

    int sum = 0;

    temp = num;

    while(temp)

    {

        sum += temp ;

        temp = temp / 10;

    }

    int res = num % sum;

    if(res == 0)

        cout << “Harshad Number”;

    else

        cout << “Not Harshad Number”;

    return 0;

}

 

JAVA 8 

// 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 ;

        temp = temp / 10;

    }

    int res = num % sum;

    if(res == 0)

        System.out.print(“Harshad Number”);

    else

        System.out.print(“Not Harshad Number”);

    }

}

 

PYTHON 3

# 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

    temp = int(temp / 10)

res = num % sum

if(res == 0):

    print(“Harshad Number”);

else:

    print(“Not Harshad Number”);
 

OUTPUT

1729

Harshad Number