The Wayback Machine - https://web.archive.org/web/20240811134702/https://www.geeksforgeeks.org/lucky-numbers/
Open In App

Lucky Numbers

Last Updated : 22 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Lucky numbers are a subset of integers. Rather than going into much theory, let us see the process of arriving at lucky 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,â€Ķâ€Ķ
First, delete every second number, we get following reduced set. 
1,3,5,7,9,11,13,15,17,19,â€Ķâ€Ķâ€Ķâ€Ķ
Now, delete every third number, we get 
1, 3, 7, 9, 13, 15, 19,….â€Ķ.
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, 13,â€Ķâ€Ķâ€Ķ

Given an integer n, write a function to say whether this number is lucky or not. 

Examples:

Input: n = 7
Output: 7 is a lucky number

Input: n = 9
Output: 9 is not a lucky number

Recommended Practice

To solve the problem follow the below idea:

Before every iteration, if we calculate the position of the given number, then in a given iteration, we can determine if the number will be deleted. Suppose calculated position for the given number is P before some iteration, and each ith number is going to be removed in this iteration, i

if P < i then input number is lucky, 
if P is such that P%i == 0 (i is a divisor of P), then input no is not lucky. 

How to calculate the Next position of  the number:

We know that initially the position of the number is nth itself. Now any next position will be equal to the previous position minus the number of elements (or say items) removed.

That is,  next_position = current_position – count of numbers removed

For example, take the case of n=13.
We have: Initial position: n, ie. 13 itself.  

1,2,3,4,5,6,7,8,9,10,11,12,13

Now after removing every second elements , we actually removed n/2 elements. So  now the position of 13 will be : n-n/2=13-6=7 (n=13),  i=2

1,3,5,7,9,11,13.

After that, we remove n/3 items. Note that n now is n=7. So position of 13 : n-n/3 = 7-7/3 = 7-2 = 5 (n=7),  i=3

1,3,7,9,13

So next it will be : n-n/4 = 5-5/4 = 4 (n=5),  i=4

1,3,7,13

So now i=5, but since position of 13 is 4 only, so it will be saved. Hence a lucky number!  n=4,  i=5

Below is the recursive implementation of the above approach:

C++
// C++ program for Lucky Numbers

#include <bits/stdc++.h>
using namespace std;

/* Returns 1 if n is a lucky no.
otherwise returns 0*/
bool isLucky(int n)
{
    static int counter = 2;

    if (counter > n)
        return 1;
    if (n % counter == 0)
        return 0;

    /*calculate next position of input no.
      Variable "next_position" is just for
    readability of the program we can
    remove it and update in "n" only */
    int next_position = n - (n / counter);

    counter++;
    return isLucky(next_position);
}

// Driver Code
int main()
{
    int x = 5;

    // Function call
    if (isLucky(x))
        cout << x << " is a lucky no.";
    else
        cout << x << " is not a lucky no.";
}

// This code is contributed
// by rathbhupendra
C
// C program for Lucky Numbers

#include <stdio.h>
#define bool int

/* Returns 1 if n is a lucky no. otherwise returns 0*/
bool isLucky(int n)
{
    static int counter = 2;

    if (counter > n)
        return 1;
    if (n % counter == 0)
        return 0;

    /*calculate next position of input no.
      Variable "next_position" is just for
    readability of the program we can
    remove it and update in "n" only */
    int next_position = n - (n / counter);

    counter++;
    return isLucky(next_position);
}

// Driver code
int main()
{
    int x = 5;

    // Function call
    if (isLucky(x))
        printf("%d is a lucky no.", x);
    else
        printf("%d is not a lucky no.", x);
    getchar();
}
Java
// Java program to check Lucky Number
import java.io.*;

class GFG {
    public static int counter = 2;

    // Returns 1 if n is a lucky no.
    // otherwise returns 0
    static boolean isLucky(int n)
    {
        if (counter > n)
            return true;
        if (n % counter == 0)
            return false;

        /*calculate next position of input no.
        Variable "next_position" is just for
        readability of the program we can
        remove it and update in "n" only */
        int next_position = n - (n / counter);

        counter++;
        return isLucky(next_position);
    }

    // Driver code
    public static void main(String[] args)
    {
        int x = 5;

        // Function call
        if (isLucky(x))
            System.out.println(x + " is a lucky no.");
        else
            System.out.println(x + " is not a lucky no.");
    }
}

// Contributed by Pramod Kumar
Python
# Python3 program to check for lucky number

# Returns 1 if n is a lucky number
# otherwise returns 0


def isLucky(n):

    # Function attribute will act
    # as static variable

    if isLucky.counter > n:
        return 1
    if n % isLucky.counter == 0:
        return 0

    # calculate next position of input no.
      # Variable "next_position" is just for
    # readability of the program we can
    # remove it and update in "n" only
    next_position = n - (n//isLucky.counter)

    isLucky.counter = isLucky.counter + 1

    return isLucky(next_position)


# Driver Code

isLucky.counter = 2  # Acts as static variable
x = 5

# Function call
if isLucky(x):
    print x, "is a Lucky number"
else:
    print x, "is not a Lucky number"

# Contributed by Harshit Agrawal
C#
// C# program to check Lucky Number
using System;

class GFG {

    public static int counter = 2;

    // Returns 1 if n is a lucky no.
    // otherwise returns 0
    static bool isLucky(int n)
    {
        if (counter > n)
            return true;
        if (n % counter == 0)
            return false;

        /*calculate next position of input no.
         Variable "next_position" is just for
         readability of the program we can
         remove it and update in "n" only */
        int next_position = n - (n / counter);

        counter++;

        return isLucky(next_position);
    }

    // Driver code
    public static void Main()
    {
        int x = 5;

        // Function call
        if (isLucky(x))
            Console.Write(x + " is a "
                          + "lucky no.");
        else
            Console.Write(x + " is not"
                          + " a lucky no.");
    }
}

// This code is contributed by
// nitin mittal.
JavaScript
<script>
 
// C++ program for Lucky Numbers  // --> not sure why it says C++
 
/* Returns 1 if n is a lucky no. 
otherwise returns 0*/
function isLucky(n,counter) {
if(counter > n) 
return 1; 
if(n % counter == 0) 
return 0; 
 
/*calculate next position of input no.
Variable "next_position" is just for 
readability of the program we can
remove it and update in "n" only */
let next_position = n - Math.floor(n/counter);
 
counter++; 
return isLucky(next_position,counter); 
} 
 
// Driver Code
 
let x = 19,counter = 2; 
if( isLucky(x,counter) )    // -->passed counter value as an argument
document.write(x + " is a lucky no."); 
else
document.write(x + " is not a lucky no."); 
 
 
// This code is contributed by Mayank Tyagi
 
</script>
 
PHP
<?php
// PHP program for Lucky Numbers

/* Returns 1 if n is a lucky 
   no. otherwise returns 0 */
function isLucky($n)
{
    $counter = 2;
    
    if($counter > $n)
        return 1;
    if($n % $counter == 0)
        return 0; 
    
    /*calculate next position of input no.
      Variable "next_position" is just for 
    readability of the program we can
    remove it and update in "n" only */
    $next_position = $n - ($n / $counter);
    
    $counter++;
    return isLucky($next_position);
}

    // Driver Code
    $x = 5;

    // Function call
    if(isLucky($x) )
        echo $x ," is a lucky no.";
    else
        echo $x ," is not a lucky no.";
        
// This code is contributed by anuj_67.
?>

Output
5 is not a lucky no.

Time Complexity: O(n)
Auxiliary Space: O(1)

Dry run of the above approach:

Let’s us take an example of 19
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,15,17,18,19,20,21,â€Ķâ€Ķ 
1,3,5,7,9,11,13,15,17,19,â€Ķ.. 
1,3,7,9,13,15,19,â€Ķâ€Ķâ€Ķ. 
1,3,7,13,15,19,â€Ķâ€Ķâ€Ķ 
1,3,7,13,19,â€Ķâ€Ķ…
In next step every 6th no .in sequence will be deleted. 19 will not be deleted after this step because position of 19 is 5th after this step. Therefore, 19 is lucky. Let’s see how above C code finds out: 


Current function call Position after this call Counter for next call Next Call isLucky(19 ) 10 3 isLucky(10) isLucky(10) 7 4 isLucky(7) isLucky(7) 6 5 isLucky(6) isLucky(6) 5 6 isLucky(5) 
 

When isLucky(6) is called, it returns 1 (because counter > n).

Please write comments if you find any bugs in the given programs or other ways to solve the same problem. 



Similar Reads

Lucky alive person in a circle | Code Solution to sword puzzle
Given n people standing in a circle where 1st has a sword, find the luckiest person in the circle, if, from 1st soldier who is has a sword each has to kill the next soldier and handover the sword to next soldier, in turn, the soldier will kill the adjacent soldier and handover the sword to next soldier such that one soldier remains in this war who
7 min read
Lucky alive person in a circle | Set - 2
Given that N person (numbered 1 to N) standing to form a circle. They all have the gun in their hand which is pointed to their leftmost Partner. Everyone shoots such that 1 shoots 2, 3 shoots 4, 5 shoots 6 .... (N-1)the shoot N (if N is even otherwise N shoots 1). Again on the second iteration, they shoot the rest of the remains as above mentioned
15+ min read
Program to check if a given number is Lucky (all digits are different)
A number is lucky if all digits of the number are different. How to check if a given number is lucky or not.Examples: Input: n = 983 Output: true All digits are different Input: n = 9838 Output: false 8 appears twice We strongly recommend you to minimize your browser and try this yourself first.The idea is to traverse through every digit of given n
13 min read
Print numbers such that no two consecutive numbers are co-prime and every three consecutive numbers are co-prime
Given an integer N, the task is to print N integers ? 109 such that no two consecutive of these integers are co-prime and every 3 consecutive are co-prime. Examples: Input: N = 3 Output: 6 15 10Input: N = 4 Output: 6 15 35 14 Approach: We can just multiply consecutive primes and for the last number just multiply the gcd(last, last-1) * 2. We do thi
15+ min read
Kth element in permutation of first N natural numbers having all even numbers placed before odd numbers in increasing order
Given two integers N and K, the task is to find the Kth element in the permutation of first N natural numbers arranged such that all the even numbers appear before the odd numbers in increasing order. Examples : Input: N = 10, K = 3 Output: 6Explanation:The required permutation is {2, 4, 6, 8, 10, 1, 3, 5, 7, 9}.The 3rd number in the permutation is
9 min read
Count of numbers of length N having prime numbers at odd indices and odd numbers at even indices
Given a number N, the task is to calculate the count of numbers of length N having prime numbers at odd indices and odd numbers at even indices. Example: Input : N = 1Output: 5Explanation : All valid numbers length 1 are 1, 3, 5, 7, 9, here we have only 1 odd index, therefore we have 5 valid numbers. Input: N = 2Output: 20 Explanation: There are 20
5 min read
Permutation of numbers such that sum of two consecutive numbers is a perfect square
Prerequisite: Hamiltonian Cycle Given an integer n(&gt;=2), find a permutation of numbers from 1 to n such that the sum of two consecutive numbers of that permutation is a perfect square. If that kind of permutation is not possible to print "No Solution". Examples: Input : 17 Output : [16, 9, 7, 2, 14, 11, 5, 4, 12, 13, 3, 6, 10, 15, 1, 8, 17] Expl
15+ min read
Numbers within a range that can be expressed as power of two numbers
Given two integers L and R. Find the number of perfect powers in the given range [L, R]. A number x is said to be perfect power if there exists some integers a &gt; 0, p &gt; 1 such that x = ap. Examples : Input : 1 4 Output : 2 Explanation : Suitable numbers are 1 and 4 where 1 can be expressed as 1 = 12 and 4 can be expressed as 4 = 22 Input : 12
12 min read
Print all distinct integers that can be formed by K numbers from a given array of N numbers
Given an array of N elements and an integer K, print all the distinct integers which can be formed by choosing K numbers from the given N numbers. A number from an array can be chosen any number of times. Examples: Input: k = 2, a[] = {3, 8, 17, 5} Output: The 10 distinct integers are: 6 8 10 11 13 16 20 22 25 34 The 2 elements chosen are: 3+3 = 6,
7 min read
Numbers less than N which are product of exactly two distinct prime numbers
Given a number [Tex]N [/Tex]. The task is to find all such numbers less than N and are a product of exactly two distinct prime numbers. For Example, 33 is the product of two distinct primes i.e 11 * 3, whereas numbers like 60 which has three distinct prime factors i.e 2 * 2 * 3 * 5.Note: These numbers cannot be a perfect square.Examples: Input : N
8 min read
three90RightbarBannerImg