I have a weird problem.
I am trying to implement the schoolbook multiplication. I am aware that the function mpz_mul does that for me but it is my task to implement it myself as a homework.
So here is my code:
void mpz_school_mul(mpz_t c, mpz_t a, mpz_t b)
{
size_t i;
mp_limb_t b_i;
mpz_t c_part;
mpz_init(c_part);
/* Backup a for the special case a := a * b. */
mpz_t a_backup;
mpz_init(a_backup);
mpz_set(a_backup, a);
/* Clear the result */
mpz_set_ui(c,0);
gmp_printf("i = %zx, size(b) = %zx, a = %Zx, b = %Zx\n", i, mpz_size(b), a, b);
for(i = 0; i < mpz_size(b); i++)
{
printf("test\n");
b_i = mpz_getlimbn(b,i);
/* c = a*b_i*B^i + ... + a*b_0*B^0 */
/* Calculate a*b_i for every round. */
mpz_mul_limb(c_part,a_backup,b_i);
/* Shift it to the right position (*B^i). */
mpz_mul_base(c_part,c_part,i);
/* Sum all a*b_i*B^i */
mpz_school_add(c, c, c_part);
}
mpz_clear(a_backup);
mpz_clear(c_part);
}
This code works well for me and i can test it with several parameters. The result is correct so I don't think I need to change to much in the calculation part. ;)
As example: This parameters work as intended.
mpz_set_str(a, "ffffffff00000000abcdabcd", 16);
mpz_set_str(b, "cceaffcc00000000abcdabcd", 16);
mpz_school_mul(c,a,b);
Now to the bug:
When i run the program with a parameter b with a zero limb (I'm using a 32 bit VM) at the end the program crashes:
mpz_set_str(a, "ffffffff00000000abcdabcd", 16);
mpz_set_str(b, "cceaffcc00000000", 16);
mpz_school_mul(c,a,b);
The output with this parameter b_0 = 0 is:
i = 0, size(b) = 2, a = ffffffff00000000abcdabcd, b = cceaffcc00000000
I think the for-loop stucks because the printf("test\n"); does not show up in this run.
Thanks for your help ;)
The bug in the problem is fixed now.
Here is the solution:
I tested out to use fprintf(stderr, "test\n"); rather than printf("test\n"); and tested the code. It magically showed up the "test" in my console. It may have to do with the wrong inclusion order of the and file.
As I had this problem with the print I didn't check my other functions. Since I figured out, that the for-loop wasn't the problem I tested several prints after each command. I was able to detect the error in the void mpz_mul_base(mpz_t c, mpz_t a, mp_size_t i) function where I didn't check the case with c_part = 0. With this parameter the following code of the mpz_mul_base(c_part,c_part,i); function ran into an endless loop:
if(mpz_size(c) >= n)
for(i = mpz_size(c); i >= n; i--)
{
mpz_setlimbn(c, clear, i);
}
I replaced the >= with > and everything works fine now.