Algorithm to find Lucky Numbers

前端 未结 10 1008
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-22 21:02

I came across this question.A number is called lucky if the sum of its digits, as well as the sum of the squares of its digits is a prime number. How many numbers between A

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-22 22:00

    I have just solved this problem.

    It's just a Dynamic Programming problem. Take DP[n](sum-square_sum) as the DP function, and DP[n](sum-square_sum) is the count of all of the numbers whose digits is less than or equal to n, with the sum and square_sum of digits of the number is respectively represented by sum and square_sum. For example:

    DP[1](1-1) = 1      # only 1 satisfies the condition                        
    DP[2](1-1) = 2      # both 1 and 10 satisfies the condition                        
    DP[3](1-1) = 3      # 1 10 100
    DP[3](2-4) = 3      # 11 110 101
    

    Since we can easily figure out the first DP state DP[1][..][..], it is:

    (0-0) => 1     (1-1) => 1    (2-4) => 1     (3-9) => 1     (4-16) => 1    
    (5-25) => 1    (6-36) => 1   (7-49) => 1    (8-64) => 1    (9-81) => 1
    

    then we can deduce DP[1] from DP[1], and then DP[3] ... DP[18] the deduce above is made by the fact that every time when n increase by 1, for example from DP[1] to DP[2], we got a new digit (0..9), and the set of (sum, square_sum) pair (i.e. DP[n]) must be updated.

    Finally, we can traverse the DP[18] set and count of the numbers that are lucky.

    Well, how about the time and space complexity of the algorithm above? As we know sum <= 18*9=162, square_sum <= 18*9*9 = 1458, so the set of (sum, square_sum) pair (i.e. DP[n]) is very small, less than 162*1458=236196, in fact it's much smaller than 236196; The fact is: my ruby program counting all the lucky numbers between 0 and 10^18 finishes in less than 1s.

    ruby lucky_numbers.rb  0.55s user 0.00s system 99% cpu 0.556 total
    

    and I test my program by writing a test function using brute force algorithm, and it's right for numbers less than 10^7 .

提交回复
热议问题