views:

358

answers:

2

I am trying to implement Pollard Rho integer factorization in C/C++.Google gives me a Java implementation of the problem here.

I don't know Java that well,so what I came up with this.My implemenation in C++ works for most cases but not in few like the one "9999", I used there.

I am aware that C++ didn't have Biginteger class so I can't have the full functionality as it gives in JAVA but I want to factorize 15 digits numbers that's sufficient for unsigned long long

Please point out what wrong in my implementation.

A: 

I've spotted one difference: the Java code assigns c and x to be new BigInteger(N.bitLength(), random), whereas the C++ code uses rand() % N, which is a smaller random range. For the value 9999, the binary is 10011100001111, so the Java code will give c and x a maximum value of 16383.

Adrian Cox
The smaller range of rand() might affect the performance when N is larger than 32767, but your explanation about what happens when N=9999 didn't make any sense to me.
GregS
I made an off by one typo: 9999 decimal is 10011100001111, and takes 14 bits to represent. If N=9999, `BigInteger(N.bitLength(), random)` will produce an integer from 0 to 2^14-1, whereas `rand() % N` will produce an integer from 0 to 9998. It's not the key bug in the code, but it's also not an accurate translation of the Java version.
Adrian Cox
+5  A: 

The problem's right here:

#define abs(x) (x>0)?(x):(-x)

You're missing some parentheses in your abs macro. Try:

#define abs(x) ((x)>0 ? (x) : -(x))

instead. (Consider what happens when abs(x-xx) is expanded in the case x-xx <= 0.)

Also, why does your gcd function return an int rather than a BigInteger?

You should also be aware that (assuming unsigned long long is a 64-bit integer type) this code won't work correctly for N larger than 2**32: if x (or xx) is greater than or equal to 2**32 then x*x will wrap modulo 2**64, giving you the wrong value for x*x % N.

Mark Dickinson
This is why inline functions are preferable to macros wherever possible.
BlueRaja - Danny Pflughoeft
Just to be clear, it's not the missing parentheses but the *misplaced* parenthesis next to the minus sign that really matters. For safely performing the multiplication, look-up SqrMod and MultiplyMod.
xan