Open In App

Implementation of Restoring Division Algorithm for unsigned integer

Last Updated : 17 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In the previous article, we have already discussed the Restoring Division Algorithm. In this article, we will discuss the implementation of this algorithm. Restoring Division Algorithm is used to divide two unsigned integers. This algorithm is used in Computer Organization and Architecture. This algorithm is called restoring because it restores the value of Accumulator(A) after each or some iterations. There is one more type i.e. Non-Restoring Division Algorithm in which value of A is not restored. Let the dividend Q = 0110 and the divisor M = 0100. The following table demonstrates the step by step solution for the given values:

  Accumulator-A(0) Dividend-Q(6) Status
Initial Values 0000 0110 0100
Step 1: Left-Shift 0000 110_  
A – M 1100   Unsuccessful(-ve)
Restoration 0000 1100  
Step 2: Left-Shift 0001 100_  
A – M 1101   Unsuccessful(-ve)
Restoration 0001 1000  
Step 3: Left-Shift 0011 000_  
A – M 1111   Unsuccessful(-ve)
Restoration 0011 0000  
Step 4: Left-Shift 0110 000_  
A – M 0010 0001 Successful(+ve)
  Remainder(2) Quotient(1)  

Approach: From the above solution, the idea is to observe that the number of steps required to compute the required quotient and remainder is equal to the number of bits in the dividend. Initially, let the dividend be Q and the divisor be M and the accumulator A = 0. Therefore:

  1. At each step, left shift the dividend by 1 position.
  2. Subtract the divisor from A(A – M).
  3. If the result is positive, then the step is said to be successful. In this case, the quotient bit will be “1” and the restoration is not required.
  4. If the result is negative, then the step is said to be unsuccessful. In this case, the quotient bit will be “0” and restoration is required.
  5. Repeat the above steps for all the bits of the dividend.

Note: Here, restoration is performed by adding back the divisor to A. 

C++




//C++ equivalent of the above code
#include <iostream>
#include <string>
#include <algorithm>
 
using namespace std;
 
// Function to add two binary numbers
string add(string A, string M) {
 
    int carry = 0;
    string Sum;
 
    // Iterating through the number
    // A. Here, it is assumed that
    // the length of both the numbers
    // is same
    for (int i = A.length() - 1; i >= 0; i--) {
        //Adding the values at both
        // the indices along with the
        //carry
        int temp = A[i] - '0' + M[i] - '0' + carry;
        // If the binary number exceeds 1
        if (temp > 1) {
            Sum.push_back('0' + (temp % 2));
            carry = 1;
        }
        else {
            Sum.push_back('0' + temp);
            carry = 0;
        }
    }
    // Return the sum from Most Significant to Low Significant
    reverse(Sum.begin(), Sum.end());
    return Sum;
}
 
// Function of find the complement of the binary number
string complement(string m) {
    string M;
 
    // Iterating through the number
    for (int i = 0; i < m.length(); i++) {
        // Computing the Complement
        M.push_back('0' + ((m[i] - '0' + 1) % 2));
    }
    // Adding 1 to the computed value
    M = add(M, "0001");
    return M;
}
 
// Function to find the quotient and remainder
// Using Restoring Division
void restoringDivision(string Q, string M, string A) {
    int count = M.length();
    //Printing the initial values
    // of the accumulator, dividend
    // and divisor
    cout << "Initial Values: A:" << A << " Q:" << Q << " M:" << M << endl;
    // The number of steps is equal to the
    // length of the binary number
    while (count > 0) {
        // Printing the values at every step
        cout << "\nstep:" << (M.length() - count + 1) << endl;
        A = A.substr(1) + Q[0];
        // Taking complement and adding it to A
        // Indirectly we are subtracting(A-M)
        string comp_M = complement(M);
        A = add(A, comp_M);
        // Left shift,assigning LSB of Q to MSB of A.
        cout << "Left Shift and Subtract: ";
        cout << " A:" << A << endl;
        cout << "A:" << A << " Q:" << Q.substr(1) << "_";
        if (A[0] == '1') {
            // Unsuccessful and Quotient bit will be zero
            Q = Q.substr(1) + '0';
            cout << "  -Unsuccessful" << endl;
            // Restoration is required for A
            A = add(A, M);
            cout << "A:" << A << " Q:" << Q << " -Restoration" << endl;
        }
        else {
            // Quotient bit will be 1
            Q = Q.substr(1) + '1';
            cout << " Successful" << endl;
            // No restoration
            cout << "A:" << A << " Q:" << Q << " -No Restoration" << endl;
        }
        count--;
    }
    // Final quotient and remainder of the
    // given dividend and divisor
    cout << "\nQuotient(Q):" << Q << " Remainder(A):" << A << endl;
}
 
int main() {
    string dividend = "0110";
    string divisor = "0100";
    string accumulator
            = string(dividend.length(), '0');
 
 
    restoringDivision(dividend, divisor, accumulator);
 
    return 0;
}


Java




import java.util.*;
//Python program to divide two
// unsigned integers using
// Restoring Division Algorithm
public class UnsignedIntDivision {
    // Function to add two binary numbers
    public static String add(String A, String M)
    {
        int carry = 0;
        StringBuilder Sum = new StringBuilder();
        // Iterating through the number
        // A. Here, it is assumed that
        // the length of both the numbers
        // is same
        for (int i = A.length() - 1; i >= 0; i--)
        {
            //Adding the values at both
            // the indices along with the
            //carry
            int temp
                    = Character.getNumericValue(A.charAt(i))
                    + Character.getNumericValue(M.charAt(i))
                    + carry;
            // If the binary number exceeds 1
            if (temp > 1) {
                Sum.append(temp % 2);
                carry = 1;
            }
            else {
                Sum.append(temp);
                carry = 0;
            }
        }
        // Return the sum from Most Significant to Low Significant
        return Sum.reverse().toString();
    }
    // Function of find the complement of the binary number
    public static String complement(String m)
    {
        StringBuilder M = new StringBuilder();
 
        // Iterating through the number
        for (int i = 0; i < m.length(); i++)
        {
            // Computing the Complement
            M.append(
                    (Character.getNumericValue(m.charAt(i)) + 1)
                            % 2);
        }
        // Adding 1 to the computed value
        M = new StringBuilder(add(M.toString(), "0001"));
        return M.toString();
    }
    // Function to find the quotient and remainder
    // Using Restoring Division
    public static void restoringDivision(String Q, String M,
                                         String A)
    {
        int count = M.length();
        //Printing the initial values
        // of the accumulator, dividend
        // and divisor
        System.out.println("Initial Values: A:" + A
                + " Q:" + Q + " M:" + M);
        // The number of steps is equal to the
        // length of the binary number
        while (count > 0) {
            // Printing the values at every step
            System.out.println("\nstep:"
                    + (M.length() - count + 1));
            A = A.substring(1) + Q.charAt(0);
            // Taking complement and adding it to A
            // Indirectly we are subtracting(A-M)
            String comp_M = complement(M);
            A = add(A, comp_M);
            // Left shift,assigning LSB of Q to MSB of A.
            System.out.print("Left Shift and Subtract: ");
            System.out.println(" A:" + A);
            System.out.print(
                    "A:" + A + " Q:" + Q.substring(1) + "_");
            if (A.charAt(0) == '1') {
                // Unsuccessful and Quotient bit will be zero
                Q = Q.substring(1) + '0';
                System.out.println("  -Unsuccessful");
                // Restoration is required for A
                A = add(A, M);
                System.out.println("A:" + A + " Q:" + Q
                        + " -Restoration");
            }
            else {
                // Quotient bit will be 1
                Q = Q.substring(1) + '1';
                System.out.println(" Successful");
                // No restoration
                System.out.println("A:" + A + " Q:" + Q
                        + " -No Restoration");
            }
            count--;
        }
        // Final quotient and remainder of the
        // given dividend and divisor
        System.out.println("\nQuotient(Q):" + Q
                + " Remainder(A):" + A);
    }
 
    public static void main(String[] args)
    {
        String dividend = "0110";
        String divisor = "0100";
        String accumulator
                = new String(new char[dividend.length()])
                .replace("\0", "0");
 
 
        restoringDivision(dividend, divisor,
                accumulator);
    }
}


Python3




# Python program to divide two
# unsigned integers using
# Restoring Division Algorithm
 
# Function to add two binary numbers
def add(A, M):
    carry = 0
    Sum = ''
 
    # Iterating through the number
    # A. Here, it is assumed that
    # the length of both the numbers
    # is same
    for i in range (len(A)-1, -1, -1):
 
        # Adding the values at both
        # the indices along with the
        # carry
        temp = int(A[i]) + int(M[i]) + carry
 
        # If the binary number exceeds 1
        if (temp>1):
            Sum += str(temp % 2)
            carry = 1
        else:
            Sum += str(temp)
            carry = 0
 
    # Returning the sum from
    # MSB to LSB
    return Sum[::-1]   
 
# Function to find the complement
# of the given binary number
def complement(m):
    M = ''
 
    # Iterating through the number
    for i in range (0, len(m)):
 
        # Computing the complement
        M += str((int(m[i]) + 1) % 2)
 
    # Adding 1 to the computed
    # value
    M = add(M, '0001')
    return M
     
# Function to find the quotient
# and remainder using the
# Restoring Division Algorithm
def restoringDivision(Q, M, A):
 
    # Computing the length of the
    # number
    count = len(M)
 
    # Printing the initial values
    # of the accumulator, dividend
    # and divisor
    print ('Initial Values: A:', A,
           ' Q:', Q, ' M:', M)
 
    # The number of steps is equal to the
    # length of the binary number
    while (count):
 
        # Printing the values at every step
        print ("\nstep:", len(M)-count + 1, end = '')
         
        # Step1: Left Shift, assigning LSB of Q
        # to MSB of A.
        print (' Left Shift and Subtract: ', end = '')
        A = A[1:] + Q[0]
 
        # Step2: Subtract the Divisor from A
        # (Perform A - M).
        comp_M = complement(M)
 
        # Taking the complement of M and
        # adding to A.
        A = add(A, comp_M)
        print(' A:', A)
        print('A:', A, ' Q:', Q[1:]+'_', end ='')
         
        if (A[0] == '1'):
 
            # The step is unsuccessful
            # and the quotient bit
            # will be '0'
            Q = Q[1:] + '0'
            print ('  -Unsuccessful')
 
            # Restoration of A is required
            A = add(A, M)
            print ('A:', A, ' Q:', Q, ' -Restoration')
             
        else:
 
            # Else, the step is successful
            # and the quotient bit
            # will be '1'
            Q = Q[1:] + '1'
            print (' Successful')
 
            # No Restoration of A.
            print ('A:', A, ' Q:',
                   Q, ' -No Restoration')
        count -= 1
 
    # Printing the final quotient
    # and remainder of the given
    # dividend and divisor.
    print ('\nQuotient(Q):', Q,
           ' Remainder(A):', A)
 
 
# Driver code
if __name__ == "__main__":
 
    dividend = '0110'
    divisor = '0100'
 
    accumulator = '0' * len(dividend)
 
    restoringDivision(dividend,
                      divisor,
                      accumulator)


C#




using System;
using System.Text;
 
class GFG {
    // Function to add two binary numbers
    public static string Add(string A, string M)
    {
        int carry = 0;
        StringBuilder Sum
            = new StringBuilder();
        // Iterating through the number
        // A. Here, it is assumed that
        // the length of both the numbers
        // is same
        for (int i = A.Length - 1; i >= 0; i--) {
            // Adding the values at both
            // the indices along with the
            // carry
            int temp = int.Parse(A[i].ToString())
                       + int.Parse(M[i].ToString()) + carry;
            // If the binary number exceeds 1
            if (temp > 1) {
                Sum.Append(temp % 2);
                carry = 1;
            }
            else {
                Sum.Append(temp);
                carry = 0;
            }
        }
        // Return the sum from Most Significant to Low
        // Significant
        char[] charArray = Sum.ToString().ToCharArray();
        Array.Reverse(charArray);
        return new string(charArray);
    }
 
    // Function of find the complement of the binary number
    public static string Complement(string m)
    {
        StringBuilder M
            = new StringBuilder();
 
        // Iterating through the number
        for (int i = 0; i < m.Length; i++) {
            // Computing the Complement
            M.Append((int.Parse(m[i].ToString()) + 1) % 2);
        }
        // Adding 1 to the computed value
        M = new StringBuilder(
            Add(M.ToString(), "0001"));
        return M.ToString();
    }
 
    // Function to find the quotient and remainder
    // Using Restoring Division
    public static void RestoringDivision(string Q, string M,
                                         string A)
    {
        int count = M.Length;
        // Printing the initial values
        // of the accumulator, dividend
        // and divisor
        Console.WriteLine("Initial Values: A:" + A
                          + " Q:" + Q + " M:" + M);
        // The number of steps is equal to the
        // length of the binary number
        while (count > 0) {
            // Printing the values at every step
            Console.WriteLine("\nstep:"
                              + (M.Length - count + 1));
            A = A.Substring(1) + Q[0];
            // Taking complement and adding it to A
            // Indirectly we are subtracting(A-M)
            string comp_M = Complement(M);
            A = Add(A, comp_M);
            // Left shift,assigning LSB of Q to MSB of A.
            Console.Write("Left Shift and Subtract: ");
            Console.WriteLine(" A:" + A);
            Console.Write("A:" + A + " Q:" + Q.Substring(1)
                          + "_");
            if (A[0] == '1') {
                // Unsuccessful and Quotient bit will be
                // zero
                Q = Q.Substring(1) + '0';
                Console.WriteLine("  -Unsuccessful");
                // Restoration is required for A
                A = Add(A, M);
                Console.WriteLine("A:" + A + " Q:" + Q
                                  + " -Restoration");
            }
            else {
                // Quotient bit will be 1
                Q = Q.Substring(1) + '1';
                Console.WriteLine(" Successful");
                // No restoration
                Console.WriteLine("A:" + A + " Q:" + Q
                                  + " -No Restoration");
            }
            count--;
        }
        // Final quotient and remainder of the
        // given dividend and divisor
        Console.WriteLine("\nQuotient(Q):" + Q
                          + " Remainder(A):" + A);
    }
     
      // Driver code
    public static void Main(string[] args)
    {
        string dividend = "0110";
        string divisor = "0100";
        string accumulator
            = new string(new char[dividend.Length])
                  .Replace("\0", "0");
         
          // Function call
        RestoringDivision(dividend, divisor, accumulator);
    }
}


Javascript




// JS program to divide two
// unsigned integers using
// Restoring Division Algorithm
 
// Function to add two binary numbers
function add(A, M)
{
    let carry = 0
    let Sum = ''
 
    // Iterating through the number
    // A. Here, it is assumed that
    // the length of both the numbers
    // is same
    for (var i = A.length - 1; i >= 0; i--)
    {
 
        // Adding the values at both
        // the indices along with the
        // carry
        temp = (A[i]) + parseInt(M[i]) + carry
 
        // If the binary number exceeds 1
        if (temp >= 1)
        {
            Sum += String(temp % 2)
            carry = 1
        }
        else
        {
            Sum += String(temp)
            carry = 0
        }
    }
    // Returning the sum from
    // MSB to LSB
    return Sum.charAt(Sum.length-1)
}
// Function to find the complement
// of the given binary number
 
function complement(m)
{
    let M = ''
 
    // Iterating through the number
    for (var i = 0; i < m.length; i++)
 
        // Computing the complement
        M += String((parseInt(m[i]) + 1) % 2)
 
    // Adding 1 to the computed
    // value
    M = add(M, '0001')
    return M
}
     
// Function to find the quotient
// and remainder using the
// Restoring Division Algorithm
function restoringDivision(Q, M, A)
{
    // Computing the length of the
    // number
    count = M.length
 
    // Printing the initial values
    // of the accumulator, dividend
    // and divisor
    console.log ('Initial Values A', A,
           ' Q', Q, ' M', M)
 
    // The number of steps is equal to the
    // length of the binary number
    while (count > 0)
    {
        // Printing the values at every step
         
        process.stdout.write("\nstep:" + (M.length-count + 1))
         
        // Step1 Left Shift, assigning LSB of Q
        // to MSB of A.
        process.stdout.write (' Left Shift and Subtract ')
        A = A[1] + Q[0]
 
        // Step2 Subtract the Divisor from A
        // (Perform A - M).
        comp_M = complement(M)
 
        // Taking the complement of M and
        // adding to A.
        A = add(A, comp_M)
        console.log(' A', A)
        process.stdout.write('A' + A + ' Q' + Q[1]+'_')
         
        if (A[0] == '1')
        {
            // The step is unsuccessful
            // and the quotient bit
            // will be '0'
            Q = Q[1] + '0'
            console.log ('  -Unsuccessful')
 
            // Restoration of A is required
            A = add(A, M)
            console.log ('A', A, ' Q', Q, ' -Restoration')
        }
        else
        {
            // Else, the step is successful
            // and the quotient bit
            // will be '1'
            Q = Q[1] + '1'
            console.log (' Successful')
 
            // No Restoration of A.
            console.log ('A', A, ' Q',
                   Q, ' -No Restoration')
        }
        count -= 1
    }
     
    // Printing the final quotient
    // and remainder of the given
    // dividend and divisor.
    console.log ('\nQuotient(Q)', Q,
           ' Remainder(A)', A)
}
 
// Driver code
let dividend = '0110'
let divisor = '0100'
 
let accumulator = '0'.repeat(dividend)
 
restoringDivision(dividend, divisor, accumulator)
 
// This code is contributed by phasing17.


Output:

Initial Values: A: 0000  Q: 0110  M: 0100

step: 1 Left Shift and Subtract:  A: 1100
A: 1100  Q: 110_  -Unsuccessful
A: 0000  Q: 1100  -Restoration

step: 2 Left Shift and Subtract:  A: 1101
A: 1101  Q: 100_  -Unsuccessful
A: 0001  Q: 1000  -Restoration

step: 3 Left Shift and Subtract:  A: 1111
A: 1111  Q: 000_  -Unsuccessful
A: 0011  Q: 0000  -Restoration

step: 4 Left Shift and Subtract:  A: 0010
A: 0010  Q: 000_ Successful
A: 0010  Q: 0001  -No Restoration

Quotient(Q): 0001  Remainder(A): 0010


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads