Thursday 27 July 2017

Java Code to find the lucky numbers for the given n value

Problem:

Another interesting sequence of numbers is produced by starting out with the list of all integers
1,2,3, ......n. From this list every second number is removed to produce a new list. From the new list every third number is removed to give yet another list. Every fourth number is removed from this list and so the process continues. The numbers that remain after this process are called the lucky numbers. Design and implement an algorithm to list the lucky numbers in the first n integers.

Solution:

package com.myprograms;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class LuckyNumbers {

public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter the Number of Elements : ");
        int n=Integer.parseInt(br.readLine());
        int a[]=new int[n];
        int c=n;
        for(int i=0;i<n;i++)
        {
            a[i]=i+1;
        }
        int del=1;
        System.out.println("\nLucky Number Operation :\n");
        while(del<n)
        {
            for(int i=del; i<n; i+=del)
            {
                for(int j=i; j<n-1; j++)
                {
                    a[j]=a[j+1];
                }
                n--;
            }
            del++;
            for(int i=0; i<n; i++)
            {
                System.out.print(a[i]+"   ");
            }
            System.out.println();
        } //end of while
        System.out.print("\nHence, the Lucky Numbers Less than "+c+" are : ");
        for(int i=0; i<n; i++)
        {
            System.out.print(a[i]+"   ");
        }
    }

}


Output:

Enter the Number of Elements : 20

Lucky Number Operation :

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  

Hence, the Lucky Numbers Less than 20 are : 1   3   7   13   19  

No comments:

Post a Comment

Program for primality test in JAVA

Problem: ============= Program for primality test in JAVA What is primality test? A primality test is an algorithm for determining wh...