A number is said to be niven or harshad if the number is divisible by the sum of its digits.
EXAMPLE-135
The sum of digits are: 1 + 3 + 5 135/9=15
A simple java program to check whether a number is harshad / niven or not can be made with the help of while loop.
For this, firstly we extract the digits of the number and then we sum up all the digits.After all the digits are summed then we check whether rhe number when divided by the sum of its digits leaves any remainder or not.
If the remainder is zero then number is niven / harshad number else not.
ALGORITHM-
STEP 1: Start STEP 2 : print "enter a number" STEP 3 : taking input of integer in n STEP 4 : int s = 0 STEP 5 : int no = n STEP 6 : repeat STEP 7 to STEP 9 until no!=0 STEP 7 : int d=no%10 STEP 8 : s=s+d STEP 9 : no=no/10 STEP 10: if (n%s==0) then goto STEP 11 else goto STEP 12 STEP 11 : print n+"is a harshad number" STEP 12 : print n+"is not a harshad number" STEP 13 : end |
JAVA CODE-
import java.util.*;
public class harshad
{
public static void main()
{
Scanner sc=new Scanner(System.in);
System.out.println("enter a number");
int n=sc.nextInt();
int s=0;
int no=n;
while(no!=0)
{
int d=no%10;
s=s+d;
no=no/10;
}
if(n%s==0)
{
System.out.println(n+" is a harshad number");
}
else
{
System.out.println(n+" is not a harshad number");
}
}
}
Output-
enter a number
135
135 is a harshad number
SIMILAR JAVA CODES-
If you find this helpful please share
Comments
Post a Comment