Lucky Numbers in Java

What are Lucky Numbers?

Consider a sequence of natural numbers:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, …
Removing every second number produces a sequence:
1, 3, 5, 7, 9, 11, 13, 15, …
Removing every third number produces a sequence:
1, 3, 7, 9, 13, 15 …
And this process continues, and we observe that some numbers remain indefinitely in the sequence. These numbers are known as Lucky Numbers.

Write a program in Java to generate and display all the lucky numbers up to a given limit. 

Example 1:
INPUT:
N = 10
OUTPUT:
Lucky numbers within 10 are:
1, 3, 7
Example 2:
INPUT:
N = 25
OUTPUT:
Lucky numbers within 25 are:
1, 3, 7, 13, 19

import java.io.*;
class LuckyNumber{
    static int gap = 2;
    public static void main(String args[])
    throws IOException{
        InputStreamReader in = new InputStreamReader(System.in);
        BufferedReader br = new BufferedReader(in);
        System.out.print("N = ");
        int n = Integer.parseInt(br.readLine());
        for(int i = 1; i <= n; i++){
            if(isLucky(i))
                System.out.print(i + "\t");
            gap = 2;
        }
    }
    public static boolean isLucky(int n){
        if(gap > n)
            return true;
        else if(n % gap == 0)
            return false;
        n = n - n / gap;
        gap++;
        return isLucky(n);
    }
}

Leave a Reply

%d bloggers like this: