Problem of the Day
A new programming or logic puzzle every Mon-Fri

Lucky Numbers

A lucky number is one that contains only 3s or only 7s (such as 77 or 333). A number can also be considered lucky if the length of the number is 3 or 7 (such as 249). Given this knowledge can you compute how many lucky numbers exist in the range [0-1000000]?

Permalink: http://problemotd.com/problem/lucky-numbers/

Comments:

  • JtMach - 9 years, 10 months ago

    Lucky Numbers: 911

    Javascript

    this.window.onload = function () {
      var luckyNumbers = 0;
      for (var index = 0; index <= 1000000; index++) {
        if(new IsNumberLucky(index.toString())) {
          this.document.writeln(index);
          luckyNumbers = luckyNumbers + 1;
        }
      }
    
      this.document.writeln("Lucky Numbers: " + luckyNumbers);
    };
    
    function IsNumberLucky(chkStr)
    {
      if (chkStr.length == 3 || chkStr.length == 7) {
        return true;
      }
    
      var validChar = "";
      if (chkStr.charAt(0) == "3" || chkStr.charAt(0) == "7") {
        validChar = chkStr.charAt(0);
      }
      else {
        return false;
      }
    
      for (var chkStrPosition = 1; chkStrPosition < chkStr.length; chkStrPosition++) {
        if (chkStr.charAt(chkStrPosition) != validChar) {
          return false;
        }
      }
    
      return true;
    }
    

    reply permalink

  • Kevin Benton - 9 years, 10 months ago

    I only got 900...

    nums = [x for x in xrange(1000000) if set(str(x)) in [set([3]), set([7])] or len(str(x)) in (7,3)]
    print len(nums)
    900
    

    reply permalink

  • Aaron Frase - 9 years, 10 months ago

    You're comparing a set of strings with a set of integers so you missed 10.

    This fixes it.

    nums = [x for x in xrange(1000000) if set(str(x)) in [set(['3']), set(['7'])] or len(str(x)) in (7,3)]

    Here was my original (much longer) version

    lucky_numbers = []
    
    for x in range(1000000):
        lucky = False
        nums = [int(i) for i in str(x)]
        s = set(nums)
        if len(s) == 1 and (s.pop() in (3, 7)):
            lucky = True
        elif len(nums) in (3, 7):
            lucky = True
        if lucky:
            lucky_numbers.append(x)
    
    print(len(lucky_numbers))
    

    reply permalink

  • slp - 9 years, 10 months ago

    Lucky Numbers: 911

    PHP

    $count = 0;
    for ($i = 0; $i <= 1000000; $i++)
    {
        $length     = strlen($i);
        $str        = (string) $i;
        $firstChar  = $str[0];
    
        if ($length == 3 || $length == 7)
            $count++;
    
        elseif (($firstChar == '3' || $firstChar == '7') && substr_count($i, $firstChar) == $length)
            $count++;
    }
    
    echo $count;
    

    reply permalink

  • Eddy - 9 years, 10 months ago

    My solution in C code using only basic arithmetic and as few lines of code as I could.

    reply permalink

Content curated by @MaxBurstein