java - Multiple Harshad Number -
system.out.print("enter 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 harshad"); break; } } if(n1%sum1==0) system.out.println("number multiple harshad"); else system.out.println("number not multiple harshad"); } } this code not working multiple harshad number. giving same output number not multiple harshad.when enter 108 gives multiple harshad when enter 8 give multiple harshad number. although 8 not multiple harshad number
sample input: 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
input: 126 output : 126 not harshad number
you forgot reset sum 0 in each iteration of outer loop. result first iteration calculates correct sum of digits.
while(n>1) { sum = 0; // add 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 harshad"); break; } }
Comments
Post a Comment