2

How can I multiply and divide without using arithmetic operators? I read similar question here but i still have problem to multiply and divide.

Also, how can square root be calculated without using math functions?

Community
  • 1
  • 1
nebula
  • 3,932
  • 13
  • 53
  • 82
  • Perhaps you can show us what you have tried. For multiple and divide you nee addition and subtraction (even if those in turn are methods instead of operators) Square root can be calculated using multiplication. – Peter Lawrey Dec 08 '11 at 09:28
  • well, i know now addition,subtraction, multiplication and division can be done with bitwise operator. But how can square root can be calculated using multiplication? – nebula Dec 08 '11 at 09:35
  • 1
    In my answer I sad that you could use Taylor series. – AlexTheo Dec 08 '11 at 09:35
  • You can also calculate log, exp, sin, cos, tan etc from multiplication and addition/subtraction. – Peter Lawrey Dec 08 '11 at 09:38
  • Taylor is a good teoretical abstraction, but as I know fastest way to calculate sqrt(a) is to use Newton method: http://en.wikipedia.org/wiki/Newton%27s_method – korifey Dec 08 '11 at 09:55

3 Answers3

2

if you have addition and negation, as in the highest voted answer to the post you gave, you can use looped additions and subtractions to implement multiplication and division.

As for the square root, just implement Newton's Iteration on the basis of the operations from step 1.

Community
  • 1
  • 1
moooeeeep
  • 31,622
  • 22
  • 98
  • 187
0

Using bitwise operators one example I found is here:

http://geeki.wordpress.com/2007/12/12/adding-two-numbers-with-bitwise-and-shift-operators/

Addition can be translated to multiplicity and division. For sqrt you could use Taylor series. http://en.wikipedia.org/wiki/Taylor_series

AlexTheo
  • 4,004
  • 1
  • 21
  • 35
0

Fast square root function(even faster than the library function!):

EDIT: not true, actually slower because of recent hardware improvements. This is however the code used in Quake II.

double fsqrt (double y)
{
    double x, z, tempf;
    unsigned long *tfptr = ((unsigned long *)&tempf) + 1;
    tempf = y;
    *tfptr = (0xbfcdd90a - *tfptr)>>1; /* estimate of 1/sqrt(y) */
    x =  tempf;
    z =  y*0.5;                        /* hoist out the “/2”    */
    x = (1.5*x) - (x*x)*(x*z);         /* iteration formula     */
    x = (1.5*x) – (x*x)*(x*z);
    // x = (1.5*x) – (x*x)*(x*z);      /* not necessary in games */
    return x*y;
}
user10F64D4
  • 6,531
  • 1
  • 13
  • 12