Ruby :: Aufgabe #67 :: Lösung #2

2 Lösungen Lösungen öffentlich
#67

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.
#2
vote_ok
von Idef1x (1320 Punkte) - 18.01.2018 um 12:40 Uhr
Quellcode ausblenden Ruby-Code
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()

Kommentare:

Für diese Lösung gibt es noch keinen Kommentar

Bitte melden Sie sich an um eine Kommentar zu schreiben.
Kommentar schreiben