Data Structure & Algorithm: Level-1 Problem #49. Lucky Number

In number theory, a lucky number is a natural number in a set which is generated by a certain “sieve”. This sieve is similar to the Sieve of Eratosthenes that generates the primes, but it eliminates numbers based on their position in the remaining set, instead of their value (or position in the initial set of natural numbers).

  • Take the set of integers 
    1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35
  • First, delete every second number, so all even numbers are gone, leaving only odd numbers. 
    1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35
  • Now, delete every third number since the first number remaining in the list after 1 is 3, we get 
    1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33
  • Continue this process indefinitely…… 
  • Any number that does NOT get deleted due to above process is called “lucky”.
  • Therefore, set of lucky numbers is 1, 3, 7, 9, 13, 15, 21, 25….

Given a number, check whether it is a lucky number or not.

Sample Input: 289

Sample Output: True


数据结构和算法:初级练习题 #49 – 幸运数


幸运数是经由类似埃拉托斯特尼筛法的算法后留下的整数集合,是在1955年波兰数学家乌拉姆提出。

  • 由一组由1开始的数列为例:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35….
  • 首先每隔一个数字删去一个,也就是将所有偶数删去,只留下奇数:1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35…
  • 现在每三个数字删去一个,因为数列里1后面的数字是3,余下的数列是:1, 3, 7, 9, 13, 15, 19, 21, 25, 27, 31, 33…
  • 现在每七个数字删去一个,因为数列里3后面的数字是7,余下的数列是:1, 3, 7, 9, 13, 15, 21, 25, 31, 33…
  • 无限重复上面的操作,最后剩下的数字就是幸运数:1, 3, 7, 9, 13, 15, 21, 25….

给定一个数字,检查它是否是幸运数。

输入样例: 289

输出样例: True


Python Solution

Lucky Numbers