jacksparrow007
jacksparrow007

Reputation: 1328

Implement division in this new programming language

X is a new programming language which allows only the following operations -

  1. You can assign zero to a variable ( as in a = 0 )
  2. You can assign one variable to another ( a=b )
  3. You can do the postincrement operation ( a++ )
  4. Negative numbers dont exist in the language. So negative numbers are taken as 0.
  5. loop(10){ //code } will execute the code ten times.
  6. You cant have comparison operators or if conditionals or bitwise operators.

Write a function to implement division in this language.

My solution so far -

Since division is repeated subtraction I'll first implement subtraction.

function decrement(var a)
{
    var x;
    loop(a)
    {
        x = a++;
     }
     return x;
}

function subtract( var a, var b )
{
    //returns a-b
     var x;
     loop(b)
     {
         x=decrement(a);
     }
     return x;
}

Now, how do i implement the division function using this subtraction?

Or any other solution without using this subtraction is also fine.

Upvotes: 1

Views: 391

Answers (1)

srivani
srivani

Reputation: 1022

// Your function (corrected)
function decrement(var a)
{
    var x = 0;
    loop(a) 
    {
        x++; a++;
    }
    return x;
}

// Your function
function subtract(var a, var b)
{
    var x;
    loop(b)
    {
        x = decrement(a);
    }
    return x;
}

// This function returns the correct value if a is divisible by b. Otherwise it returns truncate(a/b) + 1
function divide(var a, var b)
{
    var c;

    c = 0;
    loop(a)
    {
        a = subtract(a, b);
        c++;
    }
}

Upvotes: 2

Related Questions