Description:
Russian Peasant Multiplication.
This program allows one to do multiplication by just doing muliplication or division by 2 (and addition). This is interesting since computers generally use base 2 arithmetic.The algorithm is as follows. Start two rows, one with the multiplicand (say, A) and the other the multiplier (say B). The goal is to multiply A by B. The first number is successively divided by 2 while the second number is multiplied by 2. If the number in the first column is odd, then the correspoinding number in the second column is added to the sum. The final sum is the product. Example:
Multiplicand Multiplier Product
37 41 41+0 = 41
18 82
9 164 164+41 = 205
4 328
2 656
1 1312 1312+205 = 1517
Multiplicand Multiplier Product
37 41 41+0 = 41
18 82
9 164 164+41 = 205
4 328
2 656
1 1312 1312+205 = 1517
Primary Inputs: Two numbers
Primary Output: Determine the multiplication of the numbers by the above described method
Platform Used: JDK 1.6 with Notepad.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import java.io.*; class RussianMultiplication { public static void main(String[] args) { //get the input numbers Console con=System.console(); System.out.print("Enter the first number: "); int num1=Integer.parseInt(con.readLine()); System.out.print("Enter the second number: "); int num2=Integer.parseInt(con.readLine()); int product=0; if(num1%2!=0) product=product+num2; System.out.println("Multiplicand Multiplier Product"); System.out.println("\t"+num1+"\t"+num2+"\t"+product); while(num1!=1) { num1=num1/2; num2=num2*2; if(num1%2!=0) product=product+num2; System.out.println("\t"+num1+"\t"+num2+"\t"+product); } System.out.println("The product is: "+product); } } |
Your house is valueble for me. Thanks!…
Pingback: hermes replica