System.out.print("Enter a number : ");
int n = sc.nextInt();
int c, d, sum = 0,sum1=0,n1=0,count=0;
while(n>1)
{
c=n;
while(c>0)
{
d = c%10;
sum = sum + d;
c = c/10;
}
if(n%sum==0)
{
sum1=sum;
n1=n;
n=n/sum;
}
else
{
System.out.println("Not an harshad");
break;
}
}
if(n1%sum1==0)
System.out.println("Number is multiple harshad");
else
System.out.println("Number is not multiple harshad");
}
}此代码对于多个哈沙德数不能正常工作。对于一个数字,它也给出了相同的输出,不是多个harshad.when,我输入108,它给出了多个哈沙德数,但当我输入8时,它也给出了多个哈沙德数。虽然8不是多个harshad数
样本输入: 6804
Ans:
6+8+0+4=18=>6804/18=378
378=> 3+7+8=18=>378/18=21
21=> 2+1=3 =>21/3=7
输入: 126输出: 126不是哈斯哈德数
发布于 2017-08-15 20:05:05
在外部循环的每次迭代中,您都忘记将sum重置为0。因此,只有第一次迭代计算正确的位数和。
while(n>1) {
sum = 0; // add this
c=n;
while(c>0)
{
d = c%10;
sum = sum + d;
c = c/10;
}
if(n%sum==0)
{
sum1=sum;
n1=n;
n=n/sum;
}
else
{
System.out.println("Not an harshad");
break;
}
}发布于 2017-08-15 21:32:16
尝试下面的代码
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
int num = sc.nextInt();
int dividend=num;
int divisor=0;
int digit;
int count=0;
while(dividend>1){
divisor=0;
int temp=dividend;
while(temp>0){
digit = temp%10;
divisor = divisor + digit;
temp = temp/10;
}
if(dividend%divisor==0 && divisor!=1){
dividend = dividend/divisor;
count++;
}else{
break;
}
}
if(dividend==1 && count>1){
System.out.println("Number is Multiple Harshad");
}else{
System.out.println("Number is not Multiple Harshad");
}发布于 2020-12-30 22:11:07
import java.util.*;
class multiple_harshad_NUMBER {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int i = 0, s1 = 0, d = 0, s = 0, temp = 0;
int n = 6804;/*lets take it as its a multiple harshad number but if you are making a program to check whether a number is multiple harshad number or not then use Scanner class.(input)*/
while (n != 0) {
temp = n;/* assigning value to temp variable as n will be 0 at the end of inner loop*/
while (n != 0) {//loop for digit by processing
d = n % 10;
s = s + d;
n = n / 10;
}// inner looop close
s1 = temp / s;//s1 gets the quotient
if (temp % s == 0 && s != 1){//condition to check if the temp(variable) is at least harshad number
n = s1;
s = 0;
}
}// outer loop close
if (s1 == 1) {
/*since a number is a multiple harshad number if and only if the end of the snippet is 1*/
System.out.println("Is Multiple Harshad Number");
}
else {
System.out.println("Isn't Multiple Harshad Number");
}
}
}https://stackoverflow.com/questions/45692091
复制相似问题