A harshad number is one that can be divided evenly by the sum of its digits. For example, 24 is a Harshad number because 24 / (2 + 4) = 4. For example, 23 is not a Harshad number because 23 / (2 + 3) = some decimal. Here is my attempt to prompt the user for an integer, check if said integer is a Harshad number, and if it is output it; if not, keep increasing the number by 1 until we find one to output.
import java.io.*;
public class harshad {
public static void main(String[] args) throws NumberFormatException, IOException {
// TODO Auto-generated method stub
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String number = reader.readLine(); // "23"
boolean isHarshad = false;
while (isHarshad = false) {
int sum = 0;
String[] parts = number.split(""); // ["2", "3"]
int num = Integer.parseInt(number); // 23
for (int i = 0; i < parts.length; i++) {
sum += Integer.parseInt(parts[i]); // 5
}
if (num % sum == 0) { // clean division
System.out.println(num); // should work for number 24
isHarshad = true; // break loop
} else {
number = Integer.toString(num++); // "24"
}
}
}
}
question from:
https://stackoverflow.com/questions/65875393/struggling-with-harshad-algorithm-why-no-output 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…