Print lucky numbers

C program to print lucky numbers

What is a Lucky Number?
Lucky number is a natural number which can be generated by the below logic.

Consider a set of natural numbers from 1 to n.
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

Delete all second numbers in the above series.
1   3   5   7   9   11   13   15   17   19   21   23   25

Delete all third number in the above series.
1   3   7   9   13   15   19   21    25

Delete all fourth number in the above series.
1   3   7   13  15   19    25

Delete all fifth number in the above series.
1  3   7    13    19    25

Delete all sixth number in the above series.
1  3   7   13   19  

There's no seventh element to perform delete operation.  So, the above resultant numbers are the lucky numbers.

Write a C program to print lucky numbers.


  #include <stdio.h>
  #include <stdlib.h>
  int main() {
        int n, *data, index = 2, i = 0, j;

        /* get the input value n from the user */
        printf("Enter the value for n:");
        scanf("%d", &n);

        if (n <= 0) {
                printf("Invalid input!!\n");
                return 0;
        }

        /* allocate memory to store n numbers */
        data = (int *)malloc(sizeof(int) * n);


        /* store 1 to n in data array */
        while(i < n) {
                data[i] = i + 1;
                i++;
        }

        if (n < 2) {
                printf("Lucky Number is 1!!\n");
                return 0;
        }

        /* find lucky numbers */
        while (index <= n) {
                j = count = 0;

                for (i = index - 1; i < n; i = i + index) {
                                data[i] = -1;
                }


                for (i = 0; i < n; i++) {
                        if (data[i] != -1) {
                                data[j++] = data[i];
                        }
                }

                n = j;
                index++;
        }

        /* print the lucky numbers */
        printf("Lucky Numbers:");
        for (i = 0; i < n; i++) {
                printf("%d  ", data[i]);
        }
        printf("\n");
        return 0;
  }

1 comment:

  1. I got what you mean , thanks for posting .Woh I am happy to find this website through google.
    list to string in python

    ReplyDelete