Ruby :: Aufgabe #67
2 Lösungen

Alle Harshad-Zahlen von 1 bis 100 berechnen
Anfänger - Ruby
von Gustl
- 13.02.2015 um 12:35 Uhr
Eine natürliche Zahl heißt Harshad-Zahl, wenn Sie durch ihre Quersummer teilbar ist.
Beispiel: 777 ist durch 7 + 7 + 7 = 21 teilbar und ist damit eine Harshad-Zahl.
Schreibe ein Programm welches alle Harshad-Zahlen von 1 bis 100 berechnet und am Bildschirm ausgibt.
Beispiel: 777 ist durch 7 + 7 + 7 = 21 teilbar und ist damit eine Harshad-Zahl.
Schreibe ein Programm welches alle Harshad-Zahlen von 1 bis 100 berechnet und am Bildschirm ausgibt.
Lösungen:

def run puts "Gib eine Zahl, mit mindestens zwei Stellen ein:" zahl=gets #Konvertiere jedes Zeichen des Eingabe-Strings #zu einer Zahl und addiere sie zu result result=zahl[0].to_i print "Quersumme = #{zahl[0].to_i}" i=1 while i<(zahl.size-1) result+=zahl[i].to_i #Gib die dazu addierte Zahl auf der Konsole aus print " + #{zahl[i].to_i}" i+=1 end #Gib das Ergebnis der Quersumme aus puts " = #{result}" #Kontrolliere ob sich die Zahl durch ihre Quersumme ohne Rest teilen lässt if zahl.to_i%result==0 puts "#{zahl.to_i} / #{result} = #{zahl.to_i/result.to_i}" puts "#{zahl.to_i} ist also eine Harshad-Zahl!" else puts "#{zahl.to_i} / #{result} = #{zahl.to_f/result.to_f}" puts "#{zahl.to_i} ist also keine Harshad-Zahl!" end run end

def harshad_numbers() =begin In: - nothing Out: - Harshad-number from 1 to 100 =end #Section - CODE #Section - Finding the Harshad-numbers for i in 1..100 do num = i sum = 0 #Section - Getting the CrossSum on another way because of method 'digits' not working!! Math.log(num , 10).to_i.downto(-1) do |x| break if num == 0 digit = 0 digit += num / 10 ** x sum += digit num -= digit * 10 ** x end #Section - Output if i % sum == 0 puts "#{i}" end end end harshad_numbers()