Consider the sequence of natural number:-
1, 2, 3, 4, 5, 6, 7………………………………
Removing every second number produces the sequence
1, 3, 7, 9, 11, 13, 15, 17…………………………
Removing every third number from the above sequence produces the sequence
1, 3, 7, 9, 13, 15, 19, 25, 27………………………..
This process continues indefinitely by removing the fourth, fifth and so on, till after a fixed number of steps, certain natural numbers remain indefinitely. These are known as lucky numbers. Writes a program to generate and print lucky numbers less than a given natural N, where N <= 50.[2001]
import java.util.*;
public class LuckyNums
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int n;
System.out.println("Enter the number: ");
n = sc.nextInt();
int a[] = new int[n], i, j, k;
for(i=0;i<n;i++)
{
a[i] = i+1;
}
for(i=1;i<n;i++)
{
for(j=i;j<n;j=j+i)
{
for(k=j;k<n-1;k++)
a[k] = a[k+1]; //Deleting the value
n--;
}
}
System.out.println("Lucky Numbers: ");
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}
OUTPUT