wu :: forums
« wu :: forums - XOR with Arithmetic Ops »

Welcome, Guest. Please Login or Register.
May 2nd, 2025, 2:06am

RIDDLES SITE WRITE MATH! Home Home Help Help Search Search Members Members Login Login Register Register
   wu :: forums
   riddles
   cs
(Moderators: ThudnBlunder, SMQ, william wu, Eigenray, Grimbal, towr, Icarus)
   XOR with Arithmetic Ops
« Previous topic | Next topic »
Pages: 1  Reply Reply Notify of replies Notify of replies Send Topic Send Topic Print Print
   Author  Topic: XOR with Arithmetic Ops  (Read 1912 times)
R
Senior Riddler
****



Addicted!!!

   


Gender: male
Posts: 502
XOR with Arithmetic Ops  
« on: Apr 28th, 2010, 12:03am »
Quote Quote Modify Modify

How will you implement XOR operation on integers using only arithmetic operators in a certain language which does not support bitwise operations?
IP Logged

The first experience seems like Magic, but the second tells you the Trick behind it.
towr
wu::riddles Moderator
Uberpuzzler
*****



Some people are average, some are just mean.

   


Gender: male
Posts: 13730
Re: XOR with Arithmetic Ops  
« Reply #1 on: Apr 28th, 2010, 12:15am »
Quote Quote Modify Modify

One way to do it would be:
Code:
function xor(x,y)
{
  s = 2;
  r = 0;
  while (s <= x && s <= y)
  {
    r +=  (x + y) % s;
    x -= x%s;
    y -= y%s;
    s *= 2;
  }
  return r;
}
« Last Edit: Apr 28th, 2010, 12:16am by towr » IP Logged

Wikipedia, Google, Mathworld, Integer sequence DB
R
Senior Riddler
****



Addicted!!!

   


Gender: male
Posts: 502
Re: XOR with Arithmetic Ops  
« Reply #2 on: Apr 28th, 2010, 12:23am »
Quote Quote Modify Modify

Can you optimize it more? Divide and modulus are very expensive operations for Big Integers.
IP Logged

The first experience seems like Magic, but the second tells you the Trick behind it.
towr
wu::riddles Moderator
Uberpuzzler
*****



Some people are average, some are just mean.

   


Gender: male
Posts: 13730
Re: XOR with Arithmetic Ops  
« Reply #3 on: Apr 28th, 2010, 12:49am »
Quote Quote Modify Modify

I suppose we can start from the other end.
 
Code:
function xor(x,y)
{
 stack.push(1);
 while (x > stack.top() && y > stack.top())
  stack.push(stack.top() + stack.top());
 
 r=0;
 while (!stack.isempty() )
 {
  if (x >= stack.top())
  {
   x -= stack.top();  
   if (y >= stack.top())
     y -= stack.top();
   else
     r += stack.top();
  }
  else if (y >= stack.top())
  {
    y -= stack.top();
    r += stack.top();
  }
  stack.pop();
 }
 
 return r;
}
« Last Edit: Apr 28th, 2010, 12:52am by towr » IP Logged

Wikipedia, Google, Mathworld, Integer sequence DB
Pages: 1  Reply Reply Notify of replies Notify of replies Send Topic Send Topic Print Print

« Previous topic | Next topic »

Powered by YaBB 1 Gold - SP 1.4!
Forum software copyright © 2000-2004 Yet another Bulletin Board