Buch Cover Buch Cover Buch Cover Buch Cover

Web-Code: - Webcode Help

Harshad-Zahl (Schleifen)

 

Eine natürliche Zahl, die durch ihre eigene Quersumme teilbar ist, heißt Harshad- oder Niven-Zahl.

Zum Beispiel:

777 ist durch 7 + 7 + 7 = 21 teilbar und damit eine Harshad-Zahl.

Schreibe ein Programm, das alle Zahlen bis n testet, ob sie Harshad-Zahlen sind. Das Programm soll alle Harshad-Zahlen ausgeben.

0 Kommentare

Bitte melde dich an um einen Kommentar abzugeben

28 Lösung(en)

def harshad(n):
    zahl = 1
    while zahl < n:
                
        for i in range(zahl,n):
            neu = str(i) #aus der Zahl i wird ein String gebildet...
            liste = list(neu) #... der jetzt in seine Einzelteile zerlegt und diese in einer Liste gespeichert werden ...
            summe = 0           
            for item in liste:
                item = int(item) #... und nun wird jedes Einezlteil zu int konvertiert
                summe +=item #... damit alle Ziffern zur Quersumme addiert werden könen

            if i % summe  == 0:
                print (i, " ist eine Harshad-Zahl. Quersumme: ", summe)
            
            zahl+=1
            i+=1
 harshad(100)

                

Lösung von: Py Thon ()

package ch.programmieraufgaben.methoden;

import java.util.Scanner;

/**
 * Harshad Zahlen aus Programmieraufgaben.CH
 * 
 * @author Philipp Gressly (phi AT gressly DOT ch)
 */
public class HarshadZahlen {

    public static void main(String[] args) {
       new HarshadZahlen().top();
    }
    
    void top() {
      int max = einlesen("Obergrenze");
      schleife(1, max);
    }

    /**
     * Prüfe von allen Zahlen von min bis max, ob es Harshad Zahlen sind.
     */
    void schleife(int min, int max) {
       int i = min;
       while(i <= max) {
           pruefe(i);
           i = i + 1;
       }
    }
    
    

    /**
     * Prüfe auf Harshad Zahl und gib sie aus, falls es eine ist.
     */
    void pruefe(int testZahl) {
       int quersumme = quersumme(testZahl);
       if(teilbar(testZahl, quersumme)) {
           System.out.println(testZahl + " ist Harshad Zahl.");
       }
        
    }



    /**
     * Berechne die Quersumme der zahl x
     * @param testZahl
     * @return
     */
    int quersumme(int x) {
        int quersumme = 0;
        while(x > 0) {
            quersumme = quersumme + x%10;
            x = x / 10;
        }
        return quersumme;
    }

    /**
     * Prüfe auf Teilbarkeit
     */
    boolean teilbar(int zahl, int moeglicherTeiler) {
        return 0 == zahl % moeglicherTeiler; 
    }



    /**
     * Lese int ein.
     */
    Scanner sc = new Scanner(System.in);
    int einlesen(String wert) {
        System.out.println("Bitte " + wert + " eingeben: ");
        return sc.nextInt();
    }
    
}  // end of class HarshadZahlen
                

Lösung von: Philipp G. Freimann (BBW (Berufsbildungsschule Winterthur) https://www.bbw.ch)

object Harshad {
	def main(args: Array[String]): Unit = {
		print("Obergrenze eingeben: ")
		for(i <- 1 to Console.readInt) 
			if(i % i.toString.map(_.asDigit).sum == 0) println(i)
	}
}
                

Lösung von: Name nicht veröffentlicht

(defun quer-summe (n)
  "Berechnet die Quersumme einer natürlichen Zahl."
	   (if (or (not (numberp n)) (floatp n) (< n 0))
	       nil
	       (labels
		   ((q (result k)
		      (if (> k 0)
			  (q (+ result (rem k 10)) (floor k 10))
			  result)))
		 (q 0 n))))

(defun harshad (n)
  "Berechnet die Zahlen, die durch ihre eigene Quersumme teilbar sind."
  (labels
      ((h-p (k)
	 (= (rem k (quer-summe k)) 0)))
    (remove-if-not #'h-p (range 1 n))))

                

Lösung von: Stefan Meichtry (Erwachsenenbildung)

<?php
function harshad($n)
{
$checksum=0;	
$result;
for($i=1;$i<=$n;$i++)
{
		for($j=0;$j<strlen($toString="".$i);$j++)
		{
		$checksum+=$toString[$j];
		}

		if($i%$checksum==0)
		{
		echo "$i<br/>";
		}
$checksum=0;
}
}
harshad(777);

?>

                

Lösung von: Alex Hasl ()

#include <stdio.h>

int check(int i)
{
    int h = i,
		quersumme = 0;

		while(h > 9)
		{
			quersumme += h%10;
			h = h / 10;
		}
		quersumme += h;

		if(i%quersumme == 0)return 1;
		else return 0;
}

int main()
{
    int i, n;

    printf("Eingabe n: ");
    scanf("%d", &n); fflush(stdin);

    for(i = 1; i <= n; i++)
			if(check(i))printf("%d ist eine Harshadzahl.\n", i);
    return 0;
}

                

Lösung von: Christian :) (Hochschule Merseburg)

// Autor:				Andy Großhennig
// Solution for task:	Harshad-Zahl (Schleifen)

#include <iostream>

using namespace std;

// Function: Calculate the cross sum of the number
unsigned int calculateCrossSum(unsigned int iNumber)
{
	unsigned int iCrossSum = 0;

	while(iNumber != 0)
	{
		iCrossSum += iNumber % 10;	//Get the last digit of the number
		iNumber /= 10;				//delete the last digit of the number
	}

	return iCrossSum;
}

// Function: Provide a number, get their cross sum and calculate the modulo from the number through its cross sum
void checkNumb()
{	
	unsigned int iCrossSum = 0;

	// Loop: Check for Harshad number until iNumber and show if iNumber a Harshad number
	for(unsigned int iNumber = 1;iNumber <= 5000;iNumber++)
	{
		iCrossSum = calculateCrossSum(iNumber);

		if(iNumber % iCrossSum == 0) cout << iNumber << " ist eine Harshad-Zahl\n";
	}
}

int main()
{
	checkNumb();

	cout << "\n\n";
	system("Pause");
	return 0;
}
                

Lösung von: Andy Großhennig (Bundeswehr)

$in;	#eingabe
@nm;	#zahl (numbers) gesplittet
$arr;	#Menge der Zahlen
@ha;	# harshad zahlen
$hanr=0;# array feld in das die harshadzahl kommt
$zw;	#Zwischenwert beim rechnen

print"Willkommen beim Harshadzahlenrechner!\n\n";
print"Bis zu welcher Zahl wollen sie die Harshad zahlen haben? ";
chomp($in=<STDIN>);

for($i=1; $i <= $in; $i++){
	@nm=split('', $i);
	$arr=@nm;
	for($y=0 ; $y < $arr ; $y++){
		$zw += $nm[$y];		
	}
	if($i % $zw == 0){
		$ha[$hanr]=$i;
		$hanr++;
	}
	$zw=0;	
}

$arr=@ha;
for($i=0; $i < $arr; $i++){
	print $ha[$i], " ";
}
                

Lösung von: Name nicht veröffentlicht

def harshad(zahl):
    if zahl % sum([int(i) for i in str(zahl)]) == 0:
        print "ja"
    else:
        print "nein"

harshad(int(raw_input('zahl: ')))
                

Lösung von: Name nicht veröffentlicht

Dim eingabe As String 'Als String 
        Dim zähler As Integer
        Dim quersumme As Integer
        Dim ziffer As Integer

        eingabe = txtEin.Text

        For zähler = 1 To eingabe.Length

            ziffer = Mid(eingabe, zähler, 1) ' Zerteilen in einzelne Ziffern
            ziffer = CInt(ziffer) 'Zurück zu Integer um damit zu rechnen

            quersumme = quersumme + ziffer 'Alle Zahlen zusammen addieren

        Next

        If eingabe Mod quersumme = 0 Then 'Wenn kein Rest übrig bleibt ->
            txtAus.Text = " ist eine Harshard-Zahl!"
        Else
            txtAus.Text = " ist keine Harshard-zahl!"
        End If
                

Lösung von: Johannes vh ()

typeset -i max=$1 i=1 j=0 qsumme=0 
string=""

while (($i <= $max))
do
	string=$i
	while  (($j < ${#string}))
	do
		qsumme=$qsumme+${string:j:1}   #nur bei bash möglich
		j=j+1
	done
	if (($i % $qsumme == 0))
	then
		echo $i" (% "$qsumme")"
	fi
	i=$i+1
	j=0
	qsumme=0
done
                

Lösung von: Benny H. ()

#!/usr/bin/env python

harshad = int(raw_input("Enter possible Harshad value: "))
harshad_string = str(harshad)
sum = 0

for i in range(0, len(harshad_string)):
    sum += int(harshad_string[i])

if harshad % sum == 0:
    print("It's a harshad value")
else:
    print("It's not a harshad value")
                

Lösung von: Matthias Sayler (Bosch)

//Programmiersprache: Go

package main

import (
    "fmt"
    "strconv"
)

func main() {
    val, sum := 777, 0
    str := strconv.Itoa(val)

    for _, r := range str {
        n, _ := strconv.Atoi(string(r))
        sum += n
    }

    if val % sum == 0 {
        fmt.Println("Found Harshad value.")
    } else {
        fmt.Println("No Harshad value found.")
    }
}
                

Lösung von: Matthias Sayler (Bosch)

n = gets.chomp
(1..n.to_i).each do |i|
  checksum = i.to_s.split('')
  checksum.each_index {|i| checksum[i] = checksum[i].to_i}
  checksum = checksum.inject {|sum, i| sum + i}
  if i % checksum == 0
    puts i
  end
end


# gibt alle Harshad Zahlen von 1 bis einschließlich n aus
                

Lösung von: Name nicht veröffentlicht

package programmierenuebungen;

import java.util.Scanner;

/**
 *
 * @author MadDeer
 * 
 * Erklaerung: Eine Harshard-Zahl ist durch ihre Quersumme ohne Rest teilbar.
 * 
 */
public class harshardZahl {
    
    public harshardZahl(int AnfangsZahl, int EndZahl){
        calculate(AnfangsZahl, EndZahl);
    }
    
    private void calculate(int AnfangsZahl, int EndZahl) {
        for (int i = AnfangsZahl; i <= EndZahl; i++) {
            if (i % quersumme(i) == 0) {
                System.out.println("Die Zahl \"" + i + "\" ist eine Harshard-Zahl.");
            }
        }
    }
    
    private int quersumme(int zahl) {
        if (zahl < 10) {
            return zahl;
        } else {
            return zahl % 10 + quersumme((int) zahl / 10);
        }
    }
     
    public static void main(String[] args){
        //Benutzereingabe holen
        Scanner scanner = new Scanner(System.in);
        System.out.print("Anfangszahl: ");
        int anfangsZahl = Integer.parseInt(scanner.nextLine());
        System.out.println("Endzahl: ");
        int endZahl = Integer.parseInt(scanner.nextLine());
        //Benutzereingabe korrekt?
        if (anfangsZahl < endZahl && anfangsZahl > 0) {
            new harshardZahl(anfangsZahl,endZahl);
        }
    }
}
                

Lösung von: Mad Deer (FH Ulm)

def harshad(n):
    assert type(n) == int
    quersumme = sum([int(digit) for digit in str(n)])
    return n%quersumme == 0

n = int(input("Gib das Maximum n ein: "))

print(", ".join([i for i in range(1, n+1) if harshad(i)]))
                

Lösung von: Karl Welzel ()

function isHarshad(num) {
   return (num % (eval(num.toString().split("").join("+"))) == 0);
}

var arr = [], 
    n = prompt("Obergrenze:"), 
    x = 1;

for (x; x <= n; x++)
   if (isHarshad(x)) arr.push(x);
console.log(arr.join(", "));
                

Lösung von: Lisa Salander (Heidi-Klum-Gymnasium Bottrop)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace harshadZahl
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 1; i < 50; i++)
            {
                int quersumme = QuersummeErmitteln(i);
                CheckIfHarshadNumber(quersumme, i);
            }
            Console.ReadKey();
        }

        private static void CheckIfHarshadNumber(int quersumme, int i)
        {
            if (i % quersumme == 0)
                Console.WriteLine(i);
        }

        private static int QuersummeErmitteln(int i)
        {
            int quersumme = 0; 
            do
            {
                quersumme += i % 10;
                i /= 10;

            } while (i > 0);
            return quersumme;

        }
    }
}

                

Lösung von: mattia mancina (Berufsfachschule für Informatik Bozen)

$a = 1;

//Funktion um die Quersumme zu berechnen

function quersumme ($zahlen)
{
    $strZahlen = (string) $zahlen;

    for( $intQuersumme = $i = 0; $i < strlen ( $strZahlen ); $i++ )
    {
        $intQuersumme += $strZahlen{$i};
    }

    return $intQuersumme;
}


/*While-Schleife um zu überprüfen
ob die Zahlen sich durch ihre Quersumme
teilen lassen können*/

while ($a <= 2000)
{
    if ($a % quersumme($a) == 0)
    {
        if ($a % 100 == 0)
        {
            echo "<br>";
        }

        echo $a . " ";
    }
    $a++;
}

                

Lösung von: Maik Scheiermann (Powercloud GmbH)

def hartest(x):
	x2=sum([int(a) for a in str(x)])
	return True if x%x2==0 else False
for x in range(1,1000): print(x,hartest(x))
                

Lösung von: rob ert (tub)

package programmieraufgaben;

import java.util.Scanner;

/**
 *
 * @author David Wu
 */

public class Harshad_zahl {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Geben sie die Maximalzahl ein: ");
        int maxzahl = sc.nextInt();
        System.out.println("--------- Gefundene Harshad-Zahlen ------------------");
        try {
            for (int i = 1; i <= maxzahl; i++) {
                String zahl = Integer.toString(i);
                int summe = 0;
                for (int k = 0; k < zahl.length(); k++) {
                    char a = zahl.charAt(k);
                    String s = Character.toString(a);
                    summe += Integer.parseInt(s);
                }
                if (i % summe == 0) {
                    System.out.print(i+"|");
                }
            }
        }catch(ArithmeticException ae) {
            System.err.println("Division by zero");
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}

                

Lösung von: David Wu (Gut-genug.com)

function getHarshadsFromZeroToUpperLimit(upperLimit) {
    const harshads = [];
    for (let i = 0; i <= upperLimit; i++) {
        if (isHarshad(i)) harshads.push(i)
    }
    return harshads
}
function isHarshad(num) {
    let crossSum = num.toString().split("").reduce((previousValue, currentValue) => {
        return parseInt(previousValue) + parseInt(currentValue);
    }, 0)
    return num / crossSum % 1 === 0
}
getHarshadsFromZeroToUpperLimit(21)
                

Lösung von: Name nicht veröffentlicht

for i in [a for a in range(1,n) if a % sum([int(z) for z in str(a)]) == 0 ]: print(i,end = ' ')
                

Lösung von: rob ert (tub)

def harshad(limit):
    for i in range(1, limit+1):
        if i % sum([int(x) for x in str(i)]) == 0:
            yield i
print(list(harshad(21)))
                

Lösung von: Name nicht veröffentlicht

// NET 6.x | C# 10.x | VS-2022

// Variante 1 (kompakt, aber langsam, da jede Zahl in 'string' umgewandelt werden muss)
void HarshadNumbers2(int first, int last) => Enumerable.Range(first, last - first + 1).Where(x => x % x.ToString().Select(x => x - '0').Sum() == 0).ToList().ForEach(Console.WriteLine);
HarshadNumbers2(1, 1_000);

// Variante 2 (schnell; Faktor 40 gegenüber der Variante 1 bei n{ 1e9 } jeweils ohne 'Print')); 
IEnumerable<int> HarshadNumbers(int first, int last) {
    for (int i = first; i < last + 1; i++)
        if (i % DigitSum(i) == 0) yield return i;
    int DigitSum(int n) => n != 0 ? n % 10 + DigitSum(n / 10) : 0;
}

void PrintNumbers(IEnumerable<int> lst) => Console.WriteLine(string.Join("\n", lst));
PrintNumbers(HarshadNumbers(1, 1_000));
                

Lösung von: Jens Kelm (@JKooP)

// C++ 14 | VS-2022

#include <iostream>

int digit_sum(int n) {
    return n != 0 ? n % 10 + digit_sum(n / 10) : 0;
}

void harshad_numbers(int first, int last) {
    for (auto i{ first }; i < last + 1; i++)
        if (i % digit_sum(i) == 0)
            std::cout << i << "\n";
}

int main() {
    harshad_numbers(1, 1'000);
}
                

Lösung von: Jens Kelm (@JKooP)

Function DigitSum(ByVal n%)
    r% = 0
    Do While n > 0
        r = r + n Mod 10
        n = n \ 10
    Loop
    DigitSum = r
End Function

Sub PrintHarshadNumbers(ByVal first%, ByVal last%)
    For i% = first To last
        If i Mod DigitSum(i) = 0 Then Debug.Print i
    Next i
End Sub

Sub Main()
    PrintHarshadNumbers 1, 100
End Sub
                

Lösung von: Jens Kelm (@JKooP)

// C++20 | VS-2022

#include <iostream>
#include <functional>
#include <vector>

inline static const auto get_harshad_numbers(const size_t& first_, const size_t& last_) {
    static const std::function<size_t(size_t)>get_digit_sum{ [&](const auto& n_) {
    return n_ ? n_ % 10 + get_digit_sum(n_ / 10) : 0; } };

    std::vector<size_t>out;
    for (auto i{ first_ }; i < last_ + 1; ++i)
        if (i % get_digit_sum(i) == 0)
            out.push_back(i);
    return out;
}

inline static constexpr auto print(auto&& con_) {
    for (const auto& elem : con_)
        std::cout << elem << "\n";
}

int main() {
    const auto hn{ get_harshad_numbers(1, 1'000) };
    print(hn);
}
                

Lösung von: Jens Kelm (@JKooP)

Verifikation/Checksumme:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 18, 20, 21

Aktionen

Bewertung

Durchschnittliche Bewertung:

Eigene Bewertung:
Bitte zuerst anmelden

Meta

Zeit: 0.25
Schwierigkeit: Leicht
Webcode: psv4-t3wr
Autor: ()

Download PDF

Download ZIP

Zu Aufgabenblatt hinzufügen