Write a program that multiplies together two number without using arithemetic operators [duplicate]
开发者_JAVA技巧Possible Duplicate:
How to add two numbers without using ++ or + or another arithmetic operator.
Is it possible to write a program (in C) that multiplies together two number without using any arithemetic operators (*,+,-,/,%).
Below code snippet may help if you are ok with bitwise operator for addition
int xor, and, temp;
and = x & y;
xor = x ^ y;
while(and != 0 )
{
and <<= 1;
temp = xor ^ and;
and &= xor;
xor = temp;
}
For multiplying a and b add "a" "b" times
unsigned int mult(unsigned int a,unsigned int b)
{
unsigned int counter=0;
unsigned int mult = a;
if(a == 0 || b == 0)
{
return 0;
}
//Optimize if any of the number is power of two then
//Just right shift other with value of this number
while(counter < b )
{
counter = add(counter,1);
mult = add(mult,a);
}
return mult;
}
Sure - if a Turing Machine can do it, so can C (as long as you have enough memory). But you probably won't see me writing it.
If you want to do this yourself, one way would be to simulate how you might go about multiplying two numbers on paper. You work with the digits symbolically. You just need to deal with each digit and a table of results for multiplying those digits.
For adding the two numbers, a similar 'addition' table can be used.
Doesn't matter if the digits you're working with are decimal digits or binary digits - the principle is the same.
Here's how to do it using the Peasant's algorithm. add()
is from the answer Neera gave before me:
#include <stdio.h>
unsigned int add(unsigned int x, unsigned int y)
{
unsigned int xor, and, temp;
and = x & y;
xor = x ^ y;
while(and != 0 ) {
and <<= 1;
temp = xor ^ and;
and &= xor;
xor = temp;
}
return xor;
}
int main()
{
unsigned int multiplicand = 41,
multiplier = 6,
res = 0;
while(multiplier != 0) {
if (multiplier & 1) {
res = add(res, multiplicand);
}
multiplier >>= 1;
multiplicand <<= 1;
}
printf("6 times 41 equals %u\n", res);
return 0;
}
You can multiple two numbers with a Turing machine, which arguably doesn't use any arithmetic operators, just move the tape left/right, add/remove a mark from the tape. Therefore you could write a C program that emulates the Turing multiplier.
Check out the Russian Peasant Algorithm.
精彩评论