Lucky numbers are a sequence of natural numbers that remain after removing second, third, fourth, fifth and so on numbers respectively from a sequence of consecutive natural numbers.
Consider the sequence of first 20 natural numbers:
Removing every second number produces the sequence 1, 3, 5, 7, 9, 11, 13, 15, 17, 19
Next removing every third number produces the sequence 1, 3, 7, 9, 13, 15, 19
Next removing every fourth number produces the sequence 1, 3, 7, 13, 15, 19
Further deleting every fifth number we get the sequence 1, 3, 7, 13, 19
Deletion of every sixth number is not possible and the five numbers that are lucky to escape deletion remain indefinitely.
Write a program to enter any positive natural number ‘N’ where 1 <= N <= 50 and generate lucky numbers less than the given natural number.
Test your program with the following set of data:
Example 1
INPUT: N = 10
OUTPUT: LUCKY NUMBERS LESS THAN 10 ARE: 1, 3, 7
Example 2
INPUT: N = 25
OUTPUT: LUCKY NUMBERS LESS THAN 25 ARE: 1, 3, 7, 13, 19
Example 3
INPUT: N = 100
OUTPUT: NUMBER NOT IN RANGE. INVALID ENTRY
import java.util.Scanner;
class Lucky{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("N = ");
int n = Integer.parseInt(in.nextLine());
if(n < 1 || n > 50){
System.out.println("NUMBER NOT IN RANGE. INVALID ENTRY");
return;
}
int a[] = new int[n];
for(int i = 0; i < a.length; i++)
a[i] = i + 1;
int gap = 2;
while(gap <= a.length){
for(int i = gap - 1; i < a.length; i += gap)
a[i] = 0;
gap++;
a = reset(a);
}
System.out.print("LUCKY NUMBERS LESS THAN " + n + " ARE: ");
display(a);
}
public static void display(int a[]){
for(int i = 0; i < a.length; i++){
System.out.print(a[i] + " ");
}
System.out.println();
}
public static int getCount(int a[]){
int count = 0;
for(int i = 0; i < a.length; i++){
if(a[i] != 0)
count++;
}
return count;
}
public static int[] reset(int a[]){
int b[] = new int[getCount(a)];
int index = 0;
for(int i = 0; i < a.length; i++){
if(a[i] != 0)
b[index++] = a[i];
}
return b;
}
}