-1

I am trying some stuff on the 3x+1 problem and noticed when I check if this num is divisible by two comes always true even that the second iteration should be false it goes like this for 20 iterations and then start to act right. I guess it is a long number issue?

num = 3656565605161651626526625291991265161656

while num != 1:
    if (num % 2 == 0):
        num /= 2
        print("2")
    else:
        num *= 3
        num += 1
        print("3")
    num2=f'{num:.1f}'
    print(num2)

Here is the start of the result:

2
1828282802580825918440824287108404346880
2
914141401290412959220412143554202173440
2
457070700645206479610206071777101086720
2
Bros
  • 1
  • 2
  • 1
    In Python 3, `num /= 2` is float division, even if both sides are integer; try `num //= 2` – tobias_k Nov 09 '21 at 19:17
  • Why should the second iteration be `False`? 3656565605161651626526625291991265161656/2 is 1828282802580825918440824287108404346880, which is still divisible by 2. – not_speshal Nov 09 '21 at 19:21
  • so its not the check its the division going wrong... since the result doesn't make sense – Bros Nov 09 '21 at 19:28
  • I don't get this output, neither with Python 3 that yields a float after the first division, nor with Python 2 that gives integers (and correct values different from the ones in your output) . Please provide the output matching your code. – Thierry Lathuille Nov 09 '21 at 19:34
  • -Thierry Lathuille can you try the code after editing plz – Bros Nov 09 '21 at 19:46

1 Answers1

1

You need to use integer division, not float.

        num //= 2

Here are the first 20 lines of the output, where you can see it is working:

2
1828282802580825813263312645995632580828
2
914141401290412906631656322997816290414
2
457070700645206453315828161498908145207
3
1371212101935619359947484484496724435622
2
685606050967809679973742242248362217811
3
2056818152903429039921226726745086653434
2
1028409076451714519960613363372543326717
3
3085227229355143559881840090117629980152
2
1542613614677571779940920045058814990076
2
771306807338785889970460022529407495038
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30