0

i am trying to run this script and its already run for 2 days. and still dont get answer. i tried long instead int. what am i supposed to do? what is the better way to work with big numbers like this?

count=int(0)
sum1=int(1)
x=int(343543363925512)
y=int(98325112)
while x!=1:
    sum1=sum1+x
    if x%2!=0:
        x=x*3+1
    else:
         x=x/4

while y!=1:

    if y%2!=0:
        y=y*3+1
    else:
         y=y/4
    count=count+1

answer=int(sum1*count)
print answer

thank you very much.

DR.P
  • 43
  • 1
  • 7
  • 2
    modified collatz conjecture? https://www.xkcd.com/710/ (resp https://en.wikipedia.org/wiki/Collatz_conjecture) your algorithm is not proven to terminate, right? – hiro protagonist Jun 19 '17 at 16:40
  • You are doing math on huge numbers. This takes time. That's big part of the reason why the world is secure. What is the mathematical background here? Your loop will stop if x=1... Is this supposed to happen for every starting condition? Why? Have you tested your code with smaller numbers to start with? – nostradamus Jun 19 '17 at 16:40
  • 1
    When might you expect loops like these to terminate? It's not clear how quickly `x` ro `y` in this scenario would finally converge to 1, or even if they ever would, given how they're updated. This may be more of an algorithm problem than a big number handling problem. Is there a meaning behind what this is computing? – lurker Jun 19 '17 at 16:42
  • yes it based on collatz conjecture (https://en.wikipedia.org/wiki/Collatz_conjecture) . but i changed 2 in 4. so its need to work. – DR.P Jun 19 '17 at 16:45
  • What chenxingwei said. FWIW, if you change your loop exit tests to `while x > 1:` and `while y > 1:` then you should get `sum1 * count` equal to 12871366364287900, and it should run almost instantly. – PM 2Ring Jun 19 '17 at 16:57

1 Answers1

3

as I know, the problem is the famous 3n+1 problem, which could be: when the number x % 2 == 0 then you should divide 2, but not 4.

count=int(0)
sum1=int(1)
x=int(343543363925512)
y=int(98325112)
while x!=1:
    sum1=sum1+x
    if x%2!=0:
        x=x*3+1
    else:
         x=x/2

while y!=1:

    if y%2!=0:
        y=y*3+1
    else:
         y=y/2
    count=count+1

answer=int(sum1*count)
print answer

The reason why your code have been running for two days is that your function go into endless loop.

Because you only exit the loop when x or y equals to 1, when x = 2, x % 2 == 0, then you will do x / 4 which get 0, x = 0 then runs forever.

Based on your code, you could do as

while x > 1:
    //do your things here

It is >, modified, same for y.

chenxingwei
  • 251
  • 1
  • 9