Tuesday, March 15, 2022

BlueJ Program To Print Lucky Numbers


  Consider the sequence of natural numbers
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
 23, 24, 25, 26, 27, 28, 29,
Removing every second number produces the sequence
1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29„ 
Removing every third number from the above sequence produces
1, 3, 7, 9, 13, 15, 19, 21, 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.
Write a program to generate and print lucky numbers less than a given natural
 number N where N<=50.
SAMPLE
INPUT N = 10
1 2 3 4 5 6 7 8 9 
1  3  5  7  9 
1  3    7  9 
OUTPUT : THE LUCKY NUMBERS LESS THAN 10 ARE : 1 3 7
INPUT : N=25
 OUTPUT : TICE LUCKY NUMBERS LESS THAN 25 ARE 1 3 7 13 19

 import java.io.*;
class Str3
{
     int p,x,i,n,b,no;
     int arr[];
  BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    void take() throws Exception
    {      
       while(true)
       {
       System.out.print("\nEnter the range: ");
       n=Integer.parseInt(br.readLine());
       if(n<=50)
       break;
    }
    no=n;
    arr=new int[n];
    for(i=0;i<n-1;i++)
    arr[i]=i+1;
    arr[i]=-1;
    /* 'p' becomes 2,3,4,..... so that we can eliminate 2nd, 3rd, 4th position elements */
         p=2;
         while(p<=n)
         {
            x=0;
            b=0; 
       for(i=0;i<no;i++)
       {
            if(arr[i]==-1)
            break;
            b++;
            if(b%p!=0)
           {
           arr[x++]=arr[i];          
        }        
        }
       /* at the end we set -1 to denote end of elements are removal of specific location values */
        arr[x]=-1;        
        p++;
        n=b;        
    }   
    System.out.print("\nLucky Numbers as follows: ");
     for(i=0;i<no;i++)
     {     
         if(arr[i]==-1)
         break;
         System.out.print(" "+arr[i]);
        }
    }
    public static void main(String args[])throws Exception
    {
        Str3 ob=new Str3();
        ob.take();
    }
}       
  
Other Programs On Numbers: CLICK HERE

No comments:

Post a Comment

Subscribe via email

Enter your email address:

Delivered by FeedBurner