Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class UnsignedMultiplication {
- int[] decimalToBinary(int a, int n1) {
- int[] binary = new int[n1];
- int i = binary.length - 1;
- while (a != 0) {
- binary[i--] = a % 2;
- a /= 2;
- }
- return binary;
- }
- int[] add(int AQ[], int[] c) {
- int carry = 0;
- for (int i = c.length - 1; i >= 0; i--) {
- int temp = 0;
- temp = AQ[i] + c[i] + carry;
- AQ[i] = temp % 2;
- carry = temp / 2;
- }
- return AQ;
- }
- int[] shift(int AQ[]) {
- for (int i = AQ.length - 1; i >= 1; i--)
- AQ[i] = AQ[i - 1];
- AQ[0] = 0;
- return AQ;
- }
- void display(int[] AQ, int[] b, int[] c) {
- for (int i = 0; i < AQ.length; i++) {
- if (i == 1) {
- System.out.print("\t" + AQ[i]);
- continue;
- }
- if (i == c.length) {
- System.out.print("\t" + AQ[i]);
- continue;
- }
- System.out.print(AQ[i]);
- }
- System.out.print("\t");
- for (int i = 0; i < b.length; i++) {
- System.out.print(b[i]);
- }
- }
- void multiply(int a[], int b[], int c[]) {
- int AQ[] = new int[a.length + c.length];
- for (int i = 0; i < a.length; i++) {
- AQ[i + c.length] = a[i];
- }
- display(AQ, b, c);
- System.out.println();
- for (int i = 0; i < a.length; i++) {
- if (AQ[a.length + c.length - 1] == 1) {
- AQ = add(AQ, c);
- display(AQ, b, c);
- System.out.print("\t A+M\n");
- }
- shift(AQ);
- display(AQ, b, c);
- System.out.print("\t SHIFT \n");
- }
- }
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- UnsignedMultiplication u = new UnsignedMultiplication();
- System.out.println("Enter two numbers : ");
- int x = sc.nextInt();
- int y = sc.nextInt();
- int n = x > y ? x : y;
- int n1 = (int) (Math.log(n) / Math.log(2)) + 1;
- int a[] = u.decimalToBinary(x, n1);
- int b[] = u.decimalToBinary(y, n1);
- int c[] = u.decimalToBinary(y, n1 + 1);
- System.out.println("Q : " + Arrays.toString(a) + "\n" + "M : "
- + Arrays.toString(b));
- System.out.println("Carry\tA\tQ\tM");
- u.multiply(a, b, c);
- }
- }
- /*
- OUTPUT :
- Enter two numbers :
- 23
- 34
- Q : [0, 1, 0, 1, 1, 1]
- M : [1, 0, 0, 0, 1, 0]
- Carry A Q M
- 0 000000 010111 100010
- 0 100010 010111 100010 A+M
- 0 010001 001011 100010 SHIFT
- 0 110011 001011 100010 A+M
- 0 011001 100101 100010 SHIFT
- 0 111011 100101 100010 A+M
- 0 011101 110010 100010 SHIFT
- 0 001110 111001 100010 SHIFT
- 0 110000 111001 100010 A+M
- 0 011000 011100 100010 SHIFT
- 0 001100 001110 100010 SHIFT
- */
Advertisement
Add Comment
Please, Sign In to add comment