C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Program to determine whether a given number is a Harshad number
ExplanationIn this program, we need to determine whether given is Harshad or not. Harshad number A number is said to be the Harshad number if it is divisible by the sum of its digit. For example, if number is 156, then sum of its digit will be 1 + 5 + 6 = 12. Since 156 is divisible by 12. So, 156 is a Harshad number. Some of the other examples of Harshad number are 8, 54, 120, etc. To find whether the given number is a Harshad number or not, calculate the sum of the digit of the number then, check whether the given number is divisible by the sum of its digit. If yes, then given number is a Harshad number. Algorithm
SolutionPython
num = 156;
rem = sum = 0;
#Make a copy of num and store it in variable n
n = num;
#Calculates sum of digits
while(num > 0):
rem = num%10;
sum = sum + rem;
num = num//10;
#Checks whether the number is divisible by the sum of digits
if(n%sum == 0):
print(str(n) + " is a harshad number");
else:
print(str(n) + " is not a harshad number");
Output: 156 is a harshad number C
#include <stdio.h>
int main()
{
int num = 156;
int rem = 0, sum = 0, n;
//Make a copy of num and store it in variable n
n = num;
//Calculates sum of digits
while(num > 0){
rem = num%10;
sum = sum + rem;
num = num/10;
}
//Checks whether number is divisible by sum of digits
if(n%sum == 0)
printf("%d is a harshad number", n);
else
printf("%d is not a harshad number", n);
return 0;
}
Output: 156 is a harshad number JAVA
public class HarshadNumber
{
public static void main(String[] args) {
int num = 156;
int rem = 0, sum = 0, n;
//Make a copy of num and store it in variable n
n = num;
//Calculates sum of digits
while(num > 0){
rem = num%10;
sum = sum + rem;
num = num/10;
}
//Checks whether number is divisible by sum of digits
if(n%sum == 0)
System.out.println(n + " is a harshad number");
else
System.out.println(n + " is not a harshad number");
}
}
Output: 156 is a harshad number C#
using System;
public class HarshadNumber
{
public static void Main()
{
int num = 156;
int rem = 0, sum = 0, n;
//Make a copy of num and store it in variable n
n = num;
//Calculates sum of digits
while(num > 0){
rem = num%10;
sum = sum + rem;
num = num/10;
}
//Checks whether number is divisible by sum of digits
if(n%sum == 0)
Console.WriteLine(n + " is a harshad number");
else
Console.WriteLine(n + " is not a harshad number");
}
}
Output: 156 is a harshad number PHP
<!DOCTYPE html>
<html>
<body>
<?php
$num = 156;
$rem = $sum = 0;
//Make a copy of num and store it in variable n
$n = $num;
//Calculates sum of digits
while($num > 0){
$rem = $num%10;
$sum = $sum + $rem;
$num = intval($num/10);
}
//Checks whether number is divisible by sum of digits
if($n%$sum == 0)
print($n . " is a harshad number");
else
print($n . " is not a harshad number");
?>
</body>
</html>
Output: 156 is a harshad number
Next Topic#
|