001 package de.hska.java.aufgaben.kontrollstrukturen;
002
003 /**
004 * Eine <em>Harshadzahl</em> ist eine natürliche Zahl, die
005 * durch ihre Quersumme teilbar ist.
006 * Zum Beispiel ist 777 durch 7 + 7 + 7 = 21 teilbar und damit
007 * eine Harshadzahl.
008 *
009 * <p>
010 * <a href="http://www.home.hs-karlsruhe.de/~pach0003/informatik_1/aufgaben/kontrollanweisungen.html#harshad_zahl">Zurück zum Aufgabentext</a>
011 * </p>
012 *
013 *
014 * @author Christian Pape
015 *
016 */
017 public class HarshadZahl {
018
019 /**
020 * Gibt alle Harshadzahlen bis 100 aus.
021 */
022 public static void main(String[] args) {
023 for (int zahl = 1; zahl <= 100; zahl++) {
024 if (isHarshadZahl(zahl)) {
025 System.out.println(zahl);
026 }
027 }
028 }
029
030 /**
031 * Gibt genau dann <code>true</code> aus, wenn
032 * <code>zahl</code> eine Harshadzahl ist.
033 *
034 * @param zahl eine positive Zahl
035 */
036 private static boolean isHarshadZahl(final int zahl) {
037 int quersumme = 0;
038 int restlicheZiffernDerZahl = zahl;
039
040 while ( restlicheZiffernDerZahl > 0 ) {
041 quersumme += restlicheZiffernDerZahl % 10;
042 restlicheZiffernDerZahl /= 10;
043 }
044
045 return zahl % quersumme == 0;
046 }
047
048 }