Generating Lucky Numbers Program in Java

Consider the sequence of the natural numbers:
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...

Removing every second number produces:
1, 3, 5, 7, 9, ...

Removing every third number produces:
1, 3, 7, 9, ...

The process continues indefinitely by removing every 4th number, then 5th number and so on till after a fixed number of steps, certain natural numbers remain and these numbers are known as the lucky numbers.

Write a program to generate and print the lucky numbers within the range of N natural numbers.

import java.util.Scanner;
public class Lucky{
    public static void main(String args[]){
        Scanner in = new Scanner(System.in);
        System.out.print("N = ");
        int n = Integer.parseInt(in.nextLine());
        int arr[] = new int[n];
        for(int i = 0; i < n; i++)
            arr[i] = i + 1; 
        int del = 1;
        while(del < n){
            for(int i = del; i < n; i += del){
                for(int j = i; j < n - 1; j++){
                    arr[j] = arr[j + 1];
                } 
                n--;
            } 
            del++;
            for(int i = 0; i < n; i++)
                System.out.print(arr[i] + " ");
            System.out.println();
        }
        System.out.print("\nLucky numbers are: ");
        for(int i = 0; i < n; i++)
            System.out.print(arr[i]+" ");
    }   

Comments

Popular posts from this blog

Encrypt Program ISC Specimen 2023 Theory

No Repeat Program ISC Computer Science 2022 Semester 2 Theory

Bank Inheritance Program ISC Specimen 2023 Theory