Reputation: 1328
X is a new programming language which allows only the following operations -
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
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