Buch Cover Buch Cover Buch Cover Buch Cover

Web-Code: - Webcode Help

Äthiopisches Multiplizieren (Schleifen)

Äthiopisches Multiplizieren

Die Äthiopier hatten einen interessanten Weg gefunden, zwei große Zahlen miteinander zu multiplizieren.

Zunächst haben sie beiden Zahlen, die es zu multiplizieren galt, nebeneinander geschrieben ,z.B.:

17 x 34

Nun geht es aber etwas anders weiter, als wir das zu tun pflegen. Die linke Zahl wird nun für jede darunterliegende Zeile halbiert, Nachkommastellen werden abgeschnitten.

Die Rechte Zahl hingegen wird Zeile für Zeile verdoppelt. Dies wird so lange betrieben, bis die linke Zahl gleich 1 ist.

17    34

 8    68

 4   136 

 2   272

 1   544

Nun werden alle die Zeilen durchgestrichen, bei denen die linke Zahl gerade (also ohne Rest durch 2 teilbar) ist.

17    34

 8    -68- 

 4   -136- 

 2   -272- 

 1   544

Von den verbleibenden Zeilen werden die rechten Zahlen addiert, also:

17    34

 8    -- 

 4   --- 

 2   --- 

 1   544

     ====

     578

Und die Summe ist 578 - voilà! - zugleich das Ergebnis des Produkts aus 17 x 34.

Aufgabe: Schreiben Sie ein Programm, welches das Äthiopische Multiplizieren realisiert

0 Kommentare

Bitte melde dich an um einen Kommentar abzugeben

34 Lösung(en)

#include <stdio.h>
#include <stdlib.h>

#define true 1==1
#define false !true

struct _line{
	int left, right;
	int crossedOut;
	struct _line *next;
};

typedef struct _line line;

int main(int argc, char **argv) {
	int a, b, check, sum = 0;
	line *l, *iter;

	 do {
		 printf("Geben Sie den ersten Faktor ein: ");
		 check = scanf("%d",&a);
	 }
	 while(getchar() != '\n' || check != 1);

	 do {
		 printf("Geben Sie den zweiten Faktor ein: ");
	 	 check = scanf("%d",&b);
	 }
	 while(getchar() != '\n' || check != 1);

	 printf("\n%d x %d\n----------------------------\n", a, b);

	 l = malloc(sizeof(line));
	 l->left = a;
	 l->right = b;
	 l->next = NULL;

	 iter = l;

	 while(iter->left > 1){
		 line *tmp;
		 tmp = malloc(sizeof(line));
		 a /= 2;
		 b *= 2;
		 tmp->left = a;
		 tmp->right = b;
		 tmp->next = NULL;
		 iter->next = tmp;
		 iter = iter->next;
	 }

	 iter = l;

	 while(iter != NULL){
		 printf("%d %d\n", iter->left, iter->right);
		 iter = iter->next;
	 }

	 printf("----------------------------\n");

	 iter = l;

	 while(iter != NULL){
		 if(iter->left % 2 == 0){
			 iter->crossedOut = true;
			 printf("%d -%d-\n", iter->left, iter->right);
		 }
		 else{
			 iter->crossedOut = false;
			 printf("%d %d\n", iter->left, iter->right);
		 }
		 iter = iter->next;
	 }

	 printf("----------------------------\n");

	 iter = l;

	 while(iter != NULL){
		 if(iter->crossedOut){
			 printf("%d ---\n", iter->left);
		 }
		 else{
			 printf("%d -%d-\n", iter->left, iter->right);
			 sum += iter->right;
		 }
		 iter = iter->next;
	 }

	 printf("============================\n%d\n", sum);



	 return EXIT_SUCCESS;
}

                

Lösung von: André Trobisch ()



import java.util.Scanner;

public class starter {
	
	public static void main(String[] args) {
		
		Scanner sc = new Scanner(System.in);
		
		//Variablen definieren
		int result = 0;

		
		//Aufforderung zu Eingabe
		System.out.println("Willkommen beim Aethiopischen rechner");	
		System.out.println("Geben sie die erste Zahl ein");
		
		//speichern der Eingabe
		int x = sc.nextInt();
		
		//mal 2 (wegen späterem Problem)
		x*=2;
		
		//Zweite Aufforderung zu Eingabe
		System.out.println("Bitte geben sie die Zweite Zahl ein");
		
		//abspeichern der eingabe
		int y = sc.nextInt();
		
		//durch 2 (wegen späterem Probmlem)
		y/=2;
		
		//Ausgabe der Zahlen
		System.out.println( x+" X "+y);
		
		
		//Während x noch nicht 1
		while(x != 1){
			
			x/= 2;
			y*= 2;
			
			//wenn x durch 2 teilbar
			if(x%2==0){
				System.out.println(x+" \t---");
			}
			
			//wenn nicht
			else{
				System.out.println(x+" \t"+y);
				
				//y addieren zu result
				result = y + result;
			}
			
		}
		
		//ausgabe des resultats
		System.out.println("\t====");
		System.out.println("\t"+result);
	}
}

                

Lösung von: Yannick .. (It-Handbook.net)

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>

#define STR_LEN 256

bool is_odd( uint32_t n );
uint32_t aeth_mult( uint32_t a, uint32_t b );

int main( void ) {

	char out[STR_LEN] = "";

	const uint32_t a = 17;
	const uint32_t b = 34;

	uint32_t prod = aeth_mult( a, b );

	sprintf( out, "%i x %i = %i", a, b, prod );
	puts( out );

	return EXIT_SUCCESS;

}

uint32_t aeth_mult( uint32_t a, uint32_t b ) {

	uint32_t sum = 0;

	while( a >= 1 ) {

		if( is_odd( a ) ) sum += b;
		a = a >> 1;
		b = b << 1;

	}

	return sum;

}

bool is_odd( uint32_t n ) {

	return n & 1;

}

                

Lösung von: reeman :3 (TU Ilmenau)

aethiopisches = True
 
def halbieren(x):
    return x // 2
 
def verdoppeln(x):
    return x * 2
 
def istGerade(x):
    return not x % 2
 
def ethiopier(multiplikator, multiplikand):
    if aethiopisches:
        print("Das aethiopische Multiplizieren von %i und %i" % (multiplikator, multiplikand))
    ergebnis = 0
    while multiplikator >= 1:
        if istGerade(multiplikator):
            if aethiopisches:
                print("%4i %6i ---" % (multiplikator, multiplikand))
        else:
            if aethiopisches:
                print("%4i %6i " % (multiplikator, multiplikand))
            ergebnis += multiplikand
        multiplikator = halbieren(multiplikator)
        multiplikand = verdoppeln(multiplikand)
                
    if aethiopisches:
        print("%12s" % "====")
     
    return print("%11i " % ergebnis)

if __name__ == '__main__':
    print(ethiopier(17, 34))

                

Lösung von: Houssein Fofana ()

#!/usr/bin/python3
# -*- encoding: utf-8 -*-
#
#>>>autor:       Sebastian Müller
#>>>licence:    GPL
#>>>contact:    mypythonmueller@gmail.com
#

print("Programm zum multiplizieren zweier GANZER Zahlen nach äthiopischem Vorbild.")
print
erste = 0
while not erste:
    try:
        erste = int(input("Bitte die 1.Zahl eingeben: "))
    except:
        print("Eingabe war leider nicht korrekt")

zweite = 0
while not zweite:
    try:
        zweite = int(input("Bitte die 2.Zahl eingeben: "))
    except:
        print("Eingabe war leider nicht korrekt")

ergebnis = 0
while erste > 1:
    ergebnis = ergebnis + zweite if erste % 2 == 1 else ergebnis
    erste = erste // 2
    zweite += zweite
ergebnis += zweite

print(ergebnis)


                

Lösung von: Bastian Müller ()

package ch.programmieraufgaben.iteration;

import java.util.Scanner;

/**
 * Äthiopisches Multiplizieren
 * Programmieraufgabe Web-Code:064f-kdm4
 * @version 0.1 (Jul 8, 2016)
 * @author Philipp Gressly Freimann 
 *         (philipp.gressly@santis.ch)
 */
public class AethiopischesMultiplizieren {

	public static void main(String[] args) {
		new AethiopischesMultiplizieren().top();
	}


	void top() {
		int ersteZahl  = einlesenZahl("1. Faktor");
		int zweiteZahl = einlesenZahl("2. Faktor");
		int resultat   = multipliziere(ersteZahl, zweiteZahl);
		System.out.println("Produkt: " + resultat);
	}


	int multipliziere(int a, int b) {
		int produkt = 0;
		
		while(a >= 1) {
			// Nur bei ungeraden 1. Faktoren wird zum Produkt
			// dazugezählt.
			if(ungerade(a)) {
				produkt = produkt + b;
			}
			a = a / 2;
			b = b * 2;
		}
		return produkt;
	}


	boolean ungerade(int zahl) {
		return zahl != zahl/2*2;
	}


	Scanner sc = new Scanner(System.in);
	int einlesenZahl(String frage) {
		System.out.println("Bitte " + frage + " eingeben: ");
		String in = "";
		while("".equals(in) || null == in) {
			in = sc.nextLine().trim();
			try {
				int n = Integer.parseInt(in);
				return n;
			}
			catch(NumberFormatException nfx) {
				System.out.println("Kann Zahl nicht lesen.");
			}
		}
		return 0; // this must not happen.
	}


} // end of class AethiopischesMultiplizieren
                

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

// eingabemaske
document.write(
  '<input type="number" id="a" value="17"' +
    'onchange="ethiopianMultiplicationDemo()">' +
  ' × ' +
  '<input type="number" id="b" value="34"' +
   'onchange="ethiopianMultiplicationDemo()">' +
  '<p id="out"></p>'
);

function ethiopianMultiplicationDemo() {
  var a = parseInt(document.getElementById("a").value),
      b = parseInt(document.getElementById("b").value),
      out = document.getElementById("out"),
      table = '<table><tr><th>' + a + '</th><th>' + b + '</th><th>' +
        '(' + (a * b) + ')</th></tr>',
      result = b;

  while(a > 1) {
    a = Math.floor(a / 2);
    b *= 2;
    table += '<tr><td>' + a + '</td><td>';
    if (a % 2 == 0) table += '<span style="text-decoration:line-through">' +
      b + '</span>';
    else {
      table += b;
      result += b;
    }
    table += '</td><tr>';
  }

  table += '<tr><td></td><td><b>' + result + '</b></td></tr></table>';
  out.innerHTML = table; }                                 // lissalanda@gmx.at

                

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

// Äthiopischer Multiplizieren
#include <iostream>
#include <string>
using namespace std;

int main()
{
  //variablen
  int x;
  int y;
  int result=0;
  
  //aufforderung eingabe
  cout <<"Willkommen beim Aethiopischen Multiplizieren"<<endl;
  cout <<"Bitte erste Zahl eingeben"<<endl;
  cin >> x;
  
  cout <<"Bitte zweite Zahl eingeben"<<endl;
  cin >> y;
  
  //damit erste zahl angezeigt
  x*=2;
  y/=2;
  
  //starten von loop bis x = 1
  while(x!=1){
    x /= 2;
    y *=2;
    
    //teilbar durch 2
    if(x%2==0){
    cout <<x<<"\t"<<"---"<<endl;
    }
    
    //wenn nicht
    else{
    cout <<x<<"\t"<<y<<endl;   
    result +=y;
    }
  }
  
  //ausgabe des results
  cout<<"\t===="<<endl;
  cout<<"\t"<<result;
}

                

Lösung von: Yannick .. (It-Handbook.net)

using System;
using System.Collections.Generic;
using System.Linq;

namespace EthMult {
  class Program {
    static void Main() {
      Console.WriteLine(Multiply(17, 34));
      Console.ReadKey(true);
    }

    static int Multiply(int a, int b) {
      int result = 0;

      while(a > 0) {
        if(IsOdd(a)) {
          result += b;
        }

        a >>= 1;
        b <<= 1;
      }

      return result;
    }

    static bool IsOdd(int value) {
      return (value & 1) > 0;
    }
  }
}

                

Lösung von: Marcel Kapma ()

FUNCTION z_aeth_mult.
*"----------------------------------------------------------------------
*"*"Lokale Schnittstelle:
*"  IMPORTING
*"     REFERENCE(I_ZAHL_LINKS) TYPE  INT4 DEFAULT 17
*"     REFERENCE(I_ZAHL_RECHTS) TYPE  INT4 DEFAULT 34
*"  EXPORTING
*"     REFERENCE(E_ERGEBNIS) TYPE  INT4
*"----------------------------------------------------------------------

  DATA: lt_links   TYPE TABLE OF int4,
        lt_rechts  TYPE TABLE OF int4,
        lwa_links  LIKE LINE OF lt_links,
        lwa_rechts LIKE LINE OF lt_rechts,
        lhlp_cnt  TYPE int4.

* Links Halbieren rechts verdoppeln so lange bis links nur noch 1 steht
  lwa_links = i_zahl_links.
  lwa_rechts = i_zahl_rechts.
  APPEND lwa_links TO lt_links.
  APPEND lwa_rechts TO lt_rechts.
  WHILE lwa_links > 1 .
    lwa_links = lwa_links DIV 2.
    lwa_rechts = lwa_rechts * 2.
    APPEND lwa_links TO lt_links.
    APPEND lwa_rechts TO lt_rechts.
  ENDWHILE.

* Rechts addieren wo links ohne Rest halbiert werden kann
  LOOP AT lt_links INTO lwa_links.
    lhlp_cnt = lhlp_cnt + 1.
    IF ( lwa_links MOD 2 ) <> 0.
      READ TABLE lt_rechts INTO lwa_rechts INDEX lhlp_cnt.
      e_ergebnis = e_ergebnis + lwa_rechts.
    ENDIF.
  ENDLOOP.

ENDFUNCTION.
                

Lösung von: Name nicht veröffentlicht

public class Main {

	public static int first;
	public static int second;
	public static int result;

	public static void main(String[] args) {
		if(getFirst() && getSecond() && swapIfNeeded()) {
			System.out.println("");
			getResult();
			System.out.println("");
			System.out.println("Produkt: " + result);
		}
	}

	public static boolean getFirst() {
		try {
			Scanner sc = new Scanner(System.in);
			System.out.print("1. Faktor: ");
			first = sc.nextInt();
			return true;
		} catch (InputMismatchException e) {
			System.err.println("Fehler!");
			return false;
		}
	}

	public static boolean getSecond() {
		try {
			Scanner sc = new Scanner(System.in);
			System.out.print("2. Faktor: ");
			second = sc.nextInt();
			return true;
		} catch (InputMismatchException e) {
			System.err.println("Fehler!");
			return false;
		}
	}

	public static boolean swapIfNeeded() {
		if (first == 0 && second != 0) {
			first = second;
			second = 0;
			return true;
		} else if (first == 0 && second == 0) {
			System.out.println("");
			System.out.println("Produkt: " + 0);
			return false;
		}
		return true;
	}
	
	public static void getResult() {
		while (first >= 1) {
			int length = 10 - String.valueOf(first).length();
			String replace = "";
			
			if (first % 2 != 0) {
				for (int i = 0; i < length; i++) {
					if (i == length - 1) {
						replace += "+";
					} else {
						replace += " ";
					}
				}

				System.out.println(first + replace + second);
				result += second;
			} else {
				for (int i = 0; i < length; i++) {
					replace += " ";
				}

				System.out.println(first + replace + second);
			}

			first /= 2;
			second *= 2;
		}
	}
}
                

Lösung von: Name nicht veröffentlicht

<!DOCTYPE html>
<html>
<head><title>Aethiopisches Multiplizieren</title></head>
	<body>
		<h1>Aethiopisches Multiplizieren</h1>
		<hr>
		<p>Hier die zu multiplizierenden Zahlen eingeben<input type=number value="16" name="a" id="a">
		* <input type=number value="33" name="b" id="b"></p> <button onclick=multi()>Rechne!</button>
		<p name="line" id="line" >Hier erscheint hoffentlich die Loesung</p>
		 <script>
		var eins=0;
		var zwei=0;
		 var res=0;
		   var eins = document.getElementById("a").value;
		 var zwei =document.getElementById("b").value;
		Number.toInteger(eins);
		
		 function multi()
		 {
		  var bool = true;
		while (bool==true){
		if(eins > 1)
		{
		
		  if(eins%2==0)
		{
			eins = Math.floor(eins / 2);
			zwei = zwei * 2;
			
		}	
		else if(res == 0)
		{	
			eins /=2;
			eins= Math.floor(eins);
			zwei= Math.floor(zwei);
			res = res + zwei;
			zwei= zwei*2;

		}
		else
		{
			eins /=2;
			eins= Math.floor(eins);
			zwei= Math.floor(zwei);
			res = res + zwei;		
			zwei= zwei*2;

		}
		}else{
		 bool=false;
		 res = res + zwei;}
		 var result=document.getElementById("line");
		 result.innerHTML = res;
		 }
		 
		 }
		 
		 </script>
	 
	 </body>
 </html>
                

Lösung von: Theo Körling (Robert-Bosch-Berufskolleg)

var zahl1 = prompt("Wähle zahl1 aus!") *2;
var zahl2 = prompt("Wähle zahl2 aus!") /2;
var ergebnis = 0;
console.log(zahl1 + " und " + zahl2 + " sind die zu berechnenden Zahlen!");
console.log("-------------------")
while(zahl1 != 1) {
if(zahl1 != 1) {
  zahl1 = Math.floor(zahl1 / 2);
    zahl2 = Math.floor(zahl2 * 2);
  console.log(zahl1 + " " + zahl2);
}
if(zahl1 % 2 == 0) {
  console.log("Diese zahl Wegstreichen!")
} else {
  console.log("Diese Zahl Addieren!")
  ergebnis = ergebnis + zahl2;
}
}
console.log("-------------------")
console.log("Ergebnis: " + ergebnis);

                

Lösung von: Max Mergrun (HHG)

#!/usr/bin/python3

def aethiop(l,r):
        R = []
        while l > 0:
                if l % 2 == 1: R.append(r)
                l = l // 2
                r = r * 2
        return sum(R)

                

Lösung von: rob ert (tub)

Module EthMultiply

    Sub Main()
        Console.WriteLine(EthMultiply(17, 34))
        Console.ReadLine()
    End Sub

    Function EthMultiply(a As Integer, b As Integer) As Integer
        Dim aM As Integer = a
        Dim bM As Integer = b
        Dim aList As New List(Of Integer)
        Dim bList As New List(Of Integer)

        aList.Add(a)
        bList.Add(b)

        While aM > 1
            aM /= 2
            bM *= 2
            aList.Add(aM)
            bList.Add(bM)
        End While

        Dim newBList As New List(Of Integer)
        For i As Integer = 0 To aList.Count - 1
            If Not aList(i) Mod 2 = 0 Then
                newBList.Add(bList(i))
            End If
        Next

        Dim sum As Integer = 0
        For Each el In newBList
            sum += el
        Next

        Return sum
    End Function

End Module

                

Lösung von: Elias Zech (Optics Balzers)

'20.03.2017 - PowerBASIC 10

#COMPILE EXE
#DIM ALL

FUNCTION PBMAIN () AS LONG

DIM Z1 AS LONG
DIM Z2 AS LONG
DIM zw1 AS LONG
DIM zw2 AS LONG

DIM Result AS LONG

Z1 = 1200
Z2 = 13

IF Z1 MOD 2 <> 0 THEN Result += Z2

zw1 = Z1
zw2 = Z2

DO
    zw1 = INT(zw1 / 2)
    zw2 *= 2
    IF zw1 MOD 2 <> 0 THEN
        Result += zw2
    END IF
LOOP WHILE zw1 > 1

MSGBOX STR$(Z1) & " *" & STR$(Z2) & " =" & STR$(Result),,EXE.NAME$

END FUNCTION

                

Lösung von: Markus Sägesser (keine)

public class EthiopianMult {
    public static void main(String args[]){
        System.out.println(multiply(17,34));
    }

    private static int multiply(int multiplier, int multiplicand){
        int sum = multiplicand;
        while (multiplier>1){
            multiplier/=2;
            multiplicand*=2;
            if(multiplier%2!=0)
                sum+=multiplicand;
        }
        return sum;
    }
}
                

Lösung von: Hans Otto (privat)

package aethiopischesmulti;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class AethiopischesMultiplizieren {

	public static void main(String[] args) {
		Scanner inputScanner = new Scanner(System.in);
		System.out.print("Bitte Zahl a eingeben:\t"); int input1 = inputScanner.nextInt();
		System.out.print("Bitte Zahl b eingeben:\t"); int input2 = inputScanner.nextInt();
		System.out.println(calcByAethiopic(input1, input2));
	}
	
	public static int calcByAethiopic (int a, int b) {
		List<Integer> list_a = new ArrayList<Integer>();
		List<Integer> list_b = new ArrayList<Integer>();

		int sum = 0;
		for(; a>=1; a/=2, b*=2) {
			list_a.add(a);
			if( a % 2 == 1) {
				list_b.add(b);
				sum += b;
			}else{ 
				list_b.add(0);	
			}
		}
		System.out.println(list_a);
		System.out.println(list_b);
		return sum;
	}
	
}

                

Lösung von: Daniel Peters ()

public class Main {

	public static void main(String[] args) {
		
		int zahl1 = 59;
		int zahl2 = 65;
		int ergebnis;
		
		ergebnis = ethiopischesMultiplizieren(zahl1, zahl2);
		System.out.println(ergebnis);
		
	
				
	}
	public static int  ethiopischesMultiplizieren(int zahl1, int zahl2 ) {
		int ergebnis = 0;
		if(zahl1%2!=0){ ergebnis += zahl2;}	
		do {
			zahl1 /=2;
			zahl2 *=2;
			if(zahl1%2!=0){ ergebnis += zahl2;}
			
		} while (zahl1 > 1);
		
		return ergebnis;
	}
}

                

Lösung von: Name nicht veröffentlicht

<?php
# Rekrusive Methode
echo(multiply(19,25));

function multiply($x,$y,$result=0){
    if($x==1){
        return $result+$y;
    }else{
        if($x%2!=0){
            return multiply(floor($x/2),$y*2,$result+$y);
        }else{
            return multiply(floor($x/2),$y*2,$result);
        }
    }
}
                

Lösung von: Name nicht veröffentlicht

REPORT MULTI.

**************************************************************************************************
*Eingabemaske
**************************************************************************************************

SELECTION-SCREEN: BEGIN OF BLOCK b1.

    PARAMETERS: lv_z1 TYPE int4.
    PARAMETERS: lv_z2 TYPE int4.

SELECTION-SCREEN: END   OF BLOCK b1.



**************************************************************************************************
*Typisierungen
**************************************************************************************************

DATA: lv_z1a        TYPE p DECIMALS 2,          "Zahl 1: Arbeitswert
      lv_z2a        TYPE int4,                  "Zahl 2: Arbeitswert
      lv_ergeb      TYPE integer64,
      lv_floor      TYPE p DECIMALS 2.



**************************************************************************************************
*Prüfung der Eingaben
**************************************************************************************************

AT SELECTION-SCREEN.

IF lv_z1 < 0.

    MESSAGE 'Zahl 1 darf nicht negativ sein.' TYPE 'E'.

ELSEIF lv_z1 = 0.

    MESSAGE 'Zahl 1 darf nicht 0 sein.' TYPE 'E'.

ELSEIF lv_z2 < 0.

    MESSAGE 'Zahl 2 darf nicht negativ sein.' TYPE 'E'.

ELSEIF lv_z2 = 0.

    MESSAGE 'Zahl 2 darf nicht 0 sein.' TYPE 'E'.

ENDIF.



**************************************************************************************************
*Wertzuweisungen
**************************************************************************************************

lv_z1a = lv_z1.
lv_z2a = lv_z2.



*************************************************************************************************
INITIALIZATION.
*************************************************************************************************



**************************************************************************************************
*Berechnung
**************************************************************************************************

START-OF-SELECTION.

IF lv_z1 = 1.

    lv_ergeb = lv_z2.

ELSEIF lv_z2 = 1.

    lv_ergeb = lv_z1.

ENDIF.


IF lv_ergeb = 0.

    WHILE lv_z1a >= 1.

      lv_z1a = lv_z1a / 2 .

      WRITE lv_z1a.

      lv_floor = FRAC(  lv_z1a ).


      IF lv_floor <> 0.

        lv_ergeb = lv_ergeb + lv_z2a.

      ENDIF.

      lv_z2a = lv_z2a * 2.


      lv_z1a = FLOOR( lv_z1a ).

      WRITE:/ 'Z1: ', lv_z1a, '      Z2: ', lv_z2a.
      NEW-LINE.


    ENDWHILE.


ENDIF.

WRITE:/ lv_ergeb.
                

Lösung von: Name nicht veröffentlicht

package aethopie;

import java.util.Scanner;

public class Main {

	public static void main (String[] args) {
		
		Scanner scan = new Scanner(System.in);
		int istart;
		int jstart;
		int i;
		int j;
		int zwischenergebnis;
		int ergebnis;
		
		System.out.println("Geben Sie die erste zu multiplizierende Zahl ein");
		i = scan.nextInt();
		istart = i;
		
		System.out.println("Geben Sie die zweite zu multiplizierende Zahl ein");
		j = scan.nextInt();
		jstart = j;
		
		if ((i == 0) || (j == 0)) {
			
			System.out.println("Verarsch mich nicht!!!");
			
		}else if((i == 1)|| (i == -1) || (j == 1)|| (j == -1)) {
			
			System.out.println("ERNSTHAFT???!!! :C");
			
		}else {
			System.out.println(istart + " * " + jstart);
			
			System.out.println("");
			
			while((i > 1) || (i < -1)) {
				
				i /= 2;
				
				j *= 2;
				
				System.out.println(i + " * " + j);
				
				System.out.println("");
			}
			zwischenergebnis = i * j;
			
			ergebnis = jstart + zwischenergebnis;
			
			System.out.println(jstart + " + " + zwischenergebnis + " = " + ergebnis);
			
			System.out.println("");
			
			System.out.println(istart + " * " +  jstart + " = " + ergebnis);
		}
		
	}
	
}

                

Lösung von: Kevin Nickel (Emil-Fischer-Gymnasium Euskirchen)

string antwort;
            List<int> Ende = new List<int>();
            List<int> Left = new List<int>();
            int links = 0;
            do
            {
                Ende.Clear();
                Left.Clear();

                //Eingabe der linken Seite
            do
            {
                Console.Write("links ");
                string linkss = Console.ReadLine();
                bool versuch = int.TryParse(linkss, out links);
                if (links < 0)
                {
                    Console.WriteLine("Die Eingabe darf nicht kleiner als Null sein.");
                }
                if (!int.TryParse(linkss, out links))
                {
                    Console.WriteLine("Nur die Eingabe von Zahlen ist möglich.");
                    links = -1;
                }

            } while (links < 0);

            Console.WriteLine("\t" + "x");

            int rechts = 0;

                // Eingabe der rechten Seite

            do
            {
                Console.Write("rechts ");
                string rechtss = Console.ReadLine();
                bool versuch = int.TryParse(rechtss, out rechts);
                if (rechts < 0)
                {
                    Console.WriteLine("Die Eingabe darf nicht kleiner als Null sein.");
                }
                if (!int.TryParse(rechtss, out rechts))
                {
                    Console.WriteLine("Nur die Eingabe von Zahlen ist möglich.");
                    rechts = -1;
                }
            } while (rechts < 0);







            Console.WriteLine();
            Console.WriteLine(links + "\t" + rechts);

                //Berechnung und erstes Einlagern in Containern
            while (links != 1)
            {

                Ende.Add(rechts);
                Left.Add(links);
                links = links / 2;
                rechts = rechts * 2;
                Console.WriteLine(links + "\t" + rechts);

            }


            //herausfiltern aller Zahlen die durch 2 teilbar sind.
            int schleife = 0;
               
                while (schleife <= 2)
                {
                    for (int i = 0; i < Left.Count; i++)
                    {
                        if (Left[i] % 2 == 0)
                        {
                            Left.RemoveAt(i);
                            Ende.RemoveAt(i);
                        }
                    }
                    schleife++;
                }
                Ende.Add(rechts);
                Left.Add(1);

                //Ausgabe der aufzuaddierenden Zahlen
                Console.WriteLine();
                Console.WriteLine("Aufzuaddierende Zahlen:");
                for (int i = 0; i < Left.Count; i++)
                {
                    Console.WriteLine(Left[i] + "\t " + Ende[i]);
                }

                //Ausgabe der Gesamtsumme
                Console.ForegroundColor = ConsoleColor.White;
                Console.BackgroundColor = ConsoleColor.DarkRed;
                Console.WriteLine(Ende.Sum());
                Console.ResetColor();
                Console.Write("Noch ein Versuch ?");
                antwort = Convert.ToString(Console.ReadLine());
            } while (antwort == "j" || antwort == "ja");
                

Lösung von: Goo Muck (Uni)

# Step 1
def step1(left, right):

    while left[-1] != 1:
        left.append(left[-1] // 2)
        right.append(right[-1] * 2)

    return left, right

left, right = step1([17], [54])
print("Step1: Left {}".format(left))
print("Step1: Right {}".format(right))

# Step 2
def step2(left, right):

    for index in range(len(left)):
        if left[index] % 2 == 0:
            left[index] = 0
            right[index] = 0

    return left, right

left, right = step2(left, right)
print("Step2: Left {}".format(left))
print("Step2: Right {}".format(right))

# Step 3
def step3(right):

    return sum(right)

result = step3(right)
print("Step3: result {}".format(result))

                

Lösung von: Name nicht veröffentlicht

def ÄthiopischesMultiplizieren(x,y):
    A1 = [0]                # definiere Listen A1 und A2
    A2 = [0]

    while x >= 1:           # teile x durch 2 bis x_n+1 = 1 
        A1.append(x)        # Fülle Liste A1 mit den entsprechenden Itterationen
        x = int (x /2)      # speichere x als integer, um Abzurunden
    del A1[0]               # Listenkorrektur

    l = len(A1)             # Bestimme Länge der Liste A1          
    for k in range (0,l):   # iterriere y = 2*y
        A2.append(y)        # Fülle Liste A2 mit den entsprechenden Itterationen 
        y = 2*y
    del A2[0]               # Listenkorrektur

    for k in range (0,l):  # Prüfe Teilbarkeit durch 2 der Elemente von A1
        if A1[k]%2 == 0:    # setze entsprechende Einträge der Liste A2 gleich 0
            A2[k]=0

    #print (repr(A1).rjust(2), repr(A2))
            
    Prod = 0                # definiere Integer Prod zur Berechnung des Produktes von x und y
    for k in range (0,l):
        Prod = Prod + A2[k]
    return Prod 
                

Lösung von: Name nicht veröffentlicht

#include <stdio.h>

int main(){
	int i=0;
	int x,y,anzahl,ergebnis,a,b;;
	int zahlx[50];
	int zahly[50];
	printf("Bitte 1. Zahl eingeben:");
	scanf("%d",&x);
	printf("Bitte 2. Zahl eingeben:");
		scanf("%d",&y);
a=x;
b=y;

		while(x!=1){
			x=x/2;
			y=y*2;
			zahlx[i]=x;
					zahly[i]=y;
			i++;
			anzahl=i;
		}
		//printf("%d\n",x);

		for(i=0;i<anzahl;i++){
			printf("x:%d   y:%d\n",zahlx[i],zahly[i]);
			if(zahlx[i]%2!=0){
				//printf("Y: %d\n",zahly[i]);
				ergebnis+=zahly[i];

			}}
			if(a%2!=0){
				ergebnis=ergebnis+b;
			}

		printf("Das Produkt aus %d und %d lautet: %d\n",a,b,ergebnis);







	return 0;
}

                

Lösung von: Name nicht veröffentlicht

(ns mult.core)

(defn aethpschsmltplzrn
  [fa1 fa2]
(reduce (fn [x y] (+ (last x) (last y)))
        (filter (fn [x] (odd? (first x)))
                (apply map vector
                       (let [a (take-while (partial <= 1) (iterate #(quot % 2) fa1))
                             b (take (count a) (iterate #(* % 2) fa2))]
                         [a b])))))
                

Lösung von: André Trobisch ()

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

namespace Äthiopisches_Multiplizieren
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 17;
            int b = 34;
            int ergebnis = b;

            while (a > 1)
            {
                a = a / 2;
                b = b * 2;

                if (a % 2 != 0)
                {
                    ergebnis += b;

                }
            }
            Console.WriteLine(ergebnis);
            Console.ReadKey();
        }
    }
}

                

Lösung von: Chrischi Leif (S&N Datentechnik)

def aethiopischesMultiplizieren(x,y):
    res = y
    while x != 1:
        x = int(x/2)
        y *= 2
        if x % 2 == 0:
            continue
        res += y
    return res
                

Lösung von: marcus -- ()

#!/usr/bin/env raku

sub multipliziere($x, $y){
  return $y if $x == 1; # Abruchbedingung
  return multipliziere($x div 2, $y * 2) + $x mod 2 * $y # Rekursion
}

say multipliziere(17, 34);

                

Lösung von: Rc Mlz ()

#!/usr/bin/env raku

#| Erzeugt ein Subset PInt der positiven, natürlichen Zahlen.
subset PInt of UInt where * > 0;

#|{
  Multipliziert zwei natürliche Zahlen x und y mittels Äthiopischer Multiplikation.

  Es soll gelten: x > 0 sowie x <= y

  Beispiele:

  > say multipliziere_pos_int(17, 34)
  578

  > say multipliziere_pos_int(0, 17)
  Constraint type check failed in binding to parameter '$x'; expected PInt but got Int (0)

  > say multipliziere_pos_int(34, 17)
  Fehler beim Aufruf von multipliziere_pos_int(34, 17): 34 nicht <= 17 - die kleinere Zahl zuerst, bitte!

  Eine der beiden Subroutinen ist für die Abbruchbedingung $x==1
  zuständig, die andere sub für die Rekursion.

  proto wird genutzt, um für die beiden multi subs
  die Parameter $x und $y zentral zu filtern.
}
proto multipliziere_pos_int(PInt $x, PInt $y where $y >= $x || die &signatur_error_msg($x, $y) ) returns PInt {*}

sub signatur_error_msg($x, $y){
  "Fehler beim Aufruf von multipliziere_pos_int($x, $y): $x nicht <= $y - die kleinere Zahl zuerst, bitte!";
}

multi sub multipliziere_pos_int(1, $y){
  return $y
}

multi sub multipliziere_pos_int($x, $y) {
  return multipliziere_pos_int($x div 2, $y * 2) + $x mod 2 * $y
}

say PInt.WHY;
say &multipliziere_pos_int.WHY;

say multipliziere_pos_int(17, 34);
                

Lösung von: Rc Mlz ()

'''
Multipliziert zwei Integer
'''


def double_half_mult(a, b):
    import math as m

    # Bei Bedarf Faktoren tauschen
    if a < b or a % 2 == 0:
        multiplikator_left = [a]
        multiplikand_right = [b]
    else:
        multiplikator_left = [b]
        multiplikand_right = [a]
    result = 0
    count = 0

    # Multiplikatoren Listen füllen
    while multiplikator_left[count] > 1:
        multiplikator_left.append(m.floor(multiplikator_left[count] / 2))
        multiplikand_right.append(multiplikand_right[count] * 2)
        count += 1

    # Elemente streichen
    for index, value in enumerate(multiplikand_right):
        if multiplikator_left[index] % 2 == 0:
            multiplikand_right[index] = 0

    # Elemente addieren
    for value in multiplikand_right:
        result += value

    return result


print(double_half_mult(345, 230))
                

Lösung von: Name nicht veröffentlicht

// C++ 17 | VS-2022
#include <iostream>
#include <functional>

int main() {
    std::function<long(long, long)>mult{ [&](auto x, auto y) -> auto { return x == 1 ? y : mult(x / 2, y * 2) + x % 2 * y; } };
    std::cout << mult(17, 34) << "\n";
}
                

Lösung von: Jens Kelm (@JKooP)

// NET 6.x | C# 10.x | VS-2022
static long Mult(long x, long y) => x == 1 ? y : Mult(x / 2, y * 2) + x % 2 * y;
Console.WriteLine(Mult(17, 34));
                

Lösung von: Jens Kelm (@JKooP)

Aktionen

Bewertung

Durchschnittliche Bewertung:

Eigene Bewertung:
Bitte zuerst anmelden

Meta

Zeit: 1
Schwierigkeit: Mittel
Webcode: 064f-kdm4
Autor: ()

Download PDF

Download ZIP

Zu Aufgabenblatt hinzufügen