• affiliate@lemmy.world
    link
    fedilink
    arrow-up
    34
    ·
    1 year ago

    amateurs

    def is_even(n: int):
        if n ==0return True
        elif n < 0:
            return is_even(-n)
        else:
            return not is_even(n-1)
    
    • affiliate@lemmy.world
      link
      fedilink
      arrow-up
      22
      ·
      1 year ago

      here’s a constant time solution:

      def is_even(n: int):
          import math
          return sum(math.floor(abs(math.cos(math.pi/2 * n/i))) for i in range(1, 2 ** 63)) > 0
      
      spoiler

      i can’t imagine how long it’ll take to run, my computer took over 3 minutes to compute one value when the upper bound was replaced with 230. but hey, at least it’s O(1).

      • Acters@lemmy.world
        link
        fedilink
        arrow-up
        2
        ·
        1 year ago

        Nice, how about bitwise & operator?

        // n&1 is 1, then odd, else even
        
        return (!(n & 1));
        
    • Karyoplasma@discuss.tchncs.de
      link
      fedilink
      arrow-up
      2
      arrow-down
      1
      ·
      edit-2
      1 year ago

      Don’t use recursion. Each call will need to allocate a new stack frame which leads to a slower runtime than an iterative approach in pretty much any language.