Here is the algorithm (dates from Egyptian times) :
http://www.bitwisemag.com/copy/wilf/wilf...
which translates into C like this:
#include %26lt;stdio.h%26gt;
void main() {
int z = 0, x=101 , y=91;
printf("%d * %d = " , x , y);
while(x %26gt;0) {
if(x%26amp;1) { // is x odd?
z += y;
}
y %26lt;%26lt;=1; // multiple y by 2
x %26gt;%26gt;= 1; // divide x by 2
}
printf("%d" , z);
}
This works but it also needs the + operation so we need to add a function for adding. Complete code is therefore:
#include %26lt;stdio.h%26gt;
unsigned int add(unsigned int a, unsigned int b)
{
unsigned int c= 0;
unsigned int r= 0;
unsigned int t;
for (t= ~0; t; t%26gt;%26gt;= 1)
{
r%26lt;%26lt;= 1;
r|= (a^b^c)%26amp;1;
c= ((a|b)%26amp;c|a%26amp;b)%26amp;1;
a%26gt;%26gt;= 1;
b%26gt;%26gt;= 1;
}
for (t= ~0, c= ~t; t; t%26gt;%26gt;= 1)
{
c%26lt;%26lt;= 1;
c|= r%26amp;1;
r%26gt;%26gt;= 1;
}
return c;
}
unsigned int mul(unsigned int a, unsigned int b)
{
unsigned int r=0;
while(a %26gt; 0)
{
if(a%26amp;1) {
r = add(r, b);
}
b%26lt;%26lt;=1;
a%26gt;%26gt;=1;
}
return r;
}
void main()
{
unsigned int x= 101 , y = 91;
printf("%d*%d= %d\n", x , y, mul(x, y));
}
Source :
http://www.gmonline.demon.co.uk/cscene/C...
Just for info, an introduction to bitwise operators :
http://www.codeproject.com/cpp/bitbashin...
Output is simply
101 * 91 = 9191
Change the values of x and y to check other products.
In c language how to find the product of two numbers without using arithmetic operators?
simple use assignment operator, *=
ie if ya need to multiply a and b
use a*=b;
Reply:by watching the two nos.they constitute the product itself.viz 1 %26amp; 2 are two nos then product of two nos 1 %26amp; 2 is 12
Reply:The only way that I know would only work if one of the numbers was a multiple of 2.
The %26lt;%26lt; (shift left) operator effectively multiplies the number by 2 the number of times specified by the argument.
For example x %26lt;%26lt; 4 multiplies x times 2, 4 times (same as * 16).
The %26lt;%26lt;= is also another way of multiplying by a multiple of 2 and assigning the result to the left side of the equation.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment