Tuesday , 24 January 2017
Home » Array Related Programs » Program for Generating Lucky Numbers (ISC 2001) – [Method 1]

Program for Generating Lucky Numbers (ISC 2001) – [Method 1]

Question:

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 ………………………………….

Removing every second number produces the sequences
1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23 ………………………….

Removing every third number produces the sequences
1, 3, 7, 9, 13, 15, 19, 21, 25 ………………………….

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 number N.

SAMPLE INPUT :  N = 10
OUTPUT :  The Lucky numbers less than 10 are:     1     3     7

SAMPLE INPUT :  N = 25
OUTPUT :  The Lucky numbers less than 25 are:     1     3     7     13     19

Solution:

This is the 1st method, and it uses only one single dimensional array to generate the Lucky Numbers.

/**
* The class LuckyNumbers_1 generates the Lucky Numbers upto a given limit
* @author : www.javaforschool.com
* @Program Type : BlueJ Program - Java
* @Question Year : ISC 2001
*/

import java.io.*;
class LuckyNumbers_1
{
public static void main(String args[])throws 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 : 25

Lucky Number Operation :

1   3   5   7   9   11   13   15   17   19   21   23   25
1   3   7   9   13   15   19   21   25
1   3   7   13   15   19   25
1   3   7   13   19   25
1   3   7   13   19

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

Check Also

ISC 2016 Computer Science Solution + Examiner’s Comments – From the Council

Solution of ISC 2016 Computer science Paper as provided by the Council for the Indian School Certificate Examinations.

3 comments

  1. Thank you!

  2. souravsahadx@gmail.com

    Sir,is it compulsory to use User Defined functions in the practical examinations?

Leave a Reply to Ayan Choudhury Cancel reply

Your email address will not be published. Required fields are marked *