2

Is there a function that count recursive calls for Extended Euclidean algorithm function?

rechnerb :: Integer -> Integer -> (Integer,Integer,Integer)
rechnerb 0 b = (b, 0, 1)
rechnerb a b = let (g, x, y) = rechnerb (b `mod` a) a
           in (g, y - (b `div` a) * x, x)

Goob99
  • 107
  • 4
  • It would likely break [referential transparency](https://stackoverflow.com/a/9859966/67579) by counting recursive calls. – Willem Van Onsem Dec 12 '19 at 13:05
  • The simplest makeshift way is to pass another parameter to your function like `cnt` which gets incremented by one every time you make a recursive call and include it in the return value somehow.. perhaps use a tuple for the return value whereas `fst` is the answer and `snd` is the `cnt`. Kind of... – Redu Dec 12 '19 at 13:27
  • can you please write the program, I didn't really understand :/ @Redu – Goob99 Dec 12 '19 at 14:03

1 Answers1

2

You may do like

rechnerb :: Integer -> Integer -> Int -> ((Integer,Integer,Integer), Int)
rechnerb 0 b c = ((b, 0, 1), c)
rechnerb a b c = let ((g, x, y), cnt) = rechnerb (b `mod` a) a (c+1)
                 in ((g, y - (b `div` a) * x, x), cnt)

and call like;

λ> rechnerb 7 1100 1 -- last parameter is the initial value (call # 1)
((1,-157,1),3)       -- (1,-157,1) is the answer and 3 is the # of calls to rechnerb
Redu
  • 25,060
  • 6
  • 56
  • 76