Am 18.02.2013 20:13, schrieb John Immarino:
> I coded a Python solution for Problem #14 on the Project Euler website. I was 
> very surprised to find that it took 107 sec. to run even though it's a pretty 
> simple program.  I also coded an equivalent solution for the problem in the 
> old MSDOS basic. (That's the 16 bit app of 1980s vintage.)  It ran in 56 sec. 
> Is there a flaw in my coding, or is Python really this slow in this 
> particular application. MSDOS Basic usually runs at a snails pace compared to 
> Python.

> max=0
> m=0
> while m<=1000000:
>     m+=1
>     count=0
>     n=m
>     while n!=1:
>         count+=1
>         if n%2==0:
>             n=n//2
>         else:
>             n=3*n+1
>     if count>max:
>          max=count
>          num=m
> print(num,max)

I cannot compare my timings with basic but python 2.7.3 and python 3.2.3
are both equally slow hier (~50 sec).
pypy is a lot faster (only some old version 1.7.0, current versions
should be faster still) with about 5 sec.

The following C-Program:

#include <stdio.h>

int main(void) {

  int max = 0;
  int m = 0;
  long int n;
  int count;
  int num;

  while(m<=1000000) {
    m++;
    n = m;
    count = 0;

    while(n != 1) {
      count++;
      if(n % 2 == 0) {
        n = n / 2;
      }
      else {
        n = n*3 + 1;
      }
    }

    if(count > max) {
      max = count;
      num = m;
    }
  }

  printf("%d, %d\n", num, max);
}

Does the job in just under 1 sec.

Greetings
Alexander






-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to