N
N
Nicholas Lindemann2015-10-30 02:07:14
PHP
Nicholas Lindemann, 2015-10-30 02:07:14

How to translate code from C to PHP?

There is a source code for the extended Euclid algorithm written in C, you need to translate it into PHP. I tried to rewrite it, but the result of executing the code is completely different. I think pointers are the problem, since C pointers are not the same as PHP references. To understand what, and why, I could not, or most likely did not delve into the intricacies of the languages ​​themselves. Maybe someone has come across this, or knows the way to solve this problem, maybe I'm wrong in something, or I made a mistake somewhere ... I will be very grateful for any help.

/* Author:  Pate Williams (c) 1997 */

#include <stdio.h>

#define DEBUG


void extended_euclid(long a, long b, long *x, long *y, long *d)

/* calculates a * *x + b * *y = gcd(a, b) = *d */

{

  long q, r, x1, x2, y1, y2;


  if (b == 0) {

    *d = a, *x = 1, *y = 0;

    return;

  }

  x2 = 1, x1 = 0, y2 = 0, y1 = 1;

  #ifdef DEBUG
  printf("------------------------------");
  printf("-------------------\n");
  printf("q    r    x    y    a    b    ");
  printf("x2   x1   y2   y1\n");
  printf("------------------------------");
  printf("-------------------\n");
  #endif

  while (b > 0) {

    q = a / b, r = a - q * b;

    *x = x2 - q * x1, *y = y2 - q * y1;

    a = b, b = r;

    x2 = x1, x1 = *x, y2 = y1, y1 = *y;

    #ifdef DEBUG
    printf("%4ld %4ld %4ld %4ld ", q, r, *x, *y);
    printf("%4ld %4ld %4ld %4ld ", a, b, x2, x1);
    printf("%4ld %4ld\n", y2, y1);
    #endif

  }

  *d = a, *x = x2, *y = y2;

  #ifdef DEBUG
  printf("------------------------------");
  printf("-------------------\n");
  #endif

}



int main(void)
{

  long a = 4864, b = 3458, d, x, y;

  extended_euclid(a, b, &x, &y, &d);

  printf("x = %ld y = %ld d = %ld\n", x, y, d);

  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nazar Mokrinsky, 2015-10-30
@nazarpc

Let's give an example in PHP then + the difference in calculations.
Run in step-by-step debugging and see where the differences start.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question