Python Forum
Stein's GCD according to given pseudo code
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Stein's GCD according to given pseudo code
#1
Hi,
I have an assignment where I was given a pseudo code based off of Stein's algorithm to get GCD. The pseudo code provided was:
k := 0
while x and y are both even
x := x / 2
y := y / 2
k := k + 1
while x ≠ y
if x is even then x := x/2
else if y is even then y := y/2
else if x > y then x := (x – y)/2
else y := (y – x)/2
return x × 2k

I tried coding a function based off the pseudo code I was given but when I run the function, it does not solve at all. No answer is given and the code just keeps running. Can I have some help with this?

Code I wrote:
def gcd(x, y):
  k=0
  while x%2==0 and y%2==0:
    x=x/2
    y=y/2
    k=k+1
  while x%2!=0 or y%2!=0:
    while x%2==0:
      x=x/2
    while y%2==0:
      y=y/2
    while x>y:
      x=(x-y)/2
    while y>x:
      y=(y-x)/2
  return x*(2**k)
Thanks for any help!
Reply
#2
Why are you using while loops where the pseudocode is using if and else conditions? Those don't do the same thing, so you won't get the results you expect. You will only have two while loops if you tailor your Python solution to match the pseudocode you're emulating.
Reply
#3
My thought process for using while loops was that if either x or y was even, I would want to keep dividing it by 2 till the point that it would be an odd number.
I changed my code to using if and elif conditions and it worked now. I forgot that using if conditions in a while loop will cause the if conditions to loop as well.

Thanks for the help!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Write pseudo code for a class assignment Scrimshot 3 3,401 May-07-2019, 05:38 PM
Last Post: Scrimshot
  NEED HELP Pseudo-Random Numbers Kongurinn 9 5,464 Oct-23-2017, 04:17 AM
Last Post: Skaperen
  pseudo code for a quiz tsaward 4 7,701 Sep-15-2017, 09:59 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020