-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathLucky_Number.go
132 lines (104 loc) · 2.53 KB
/
Lucky_Number.go
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
/* This program prints lucky numbers till a given number n. Lucky
number - It is a set of numbers which is formed by eliminating
numbers based on their position based on the remaining set.*/
package main
import (
"fmt"
)
func lucky_number(number int) {
// This array stores the lucky numbers
array := make([]int, number)
// This array is used for eliminating
count := make([]int, number)
// This array is used for terminating
check := make([]int, number)
check[0] = 0
// Fill the array with numbers from 1 to n
for i := 0; i < number; i++ {
array[i] = i + 1
count[i] = i + 1
}
// First case where every second number is eliminated
var counter int = 1
for i := counter; i < number; i += 2 {
array[i] = -1
count[i] = -1
}
// Updating the count array for further eliminations
var cnt int = 0
for i := 0; i < number; i++ {
if(count[i] != -1) {
count[i] = cnt + 1
cnt++
}
}
counter = 3
var same int = 0
var value int = 1
// For further forming the series of lucky numbers
for {
same = 0
/* Updating the value of array of lucky number
according to the count array.*/
for i := 0; i < number; i++ {
if(count[i] % counter == 0) {
array[i] = -1
}
}
// Setting the count array to initial state
for i := 0; i < number; i++ {
count[i] = -1
}
// Forming the count array for next set of eliminations
cnt = 0
for i := 0; i < number; i++ {
if(array[i] != -1) {
count[i] = cnt + 1
cnt++
} else {
// Keeping a track of number of -1's in array
same += 1
}
}
// Filling number of -1's at each iteration
check[value] = same
// Finding the next index to eliminate from
for i := counter; i < number; i++ {
if(array[i] != -1) {
counter = array[i]
break
}
}
// Terminating step
if(check[value] == check[value - 1]) {
/* If the number of -1's don't change in
two successive operations, exit the loop.*/
break
}
value += 1
}
// Print the lucky numbers
for i := 0; i < number; i++ {
if(array[i] != -1) {
fmt.Print(array[i], " ")
}
}
fmt.Print("\n")
}
func main() {
// Take number as input from the user
var number int
fmt.Print("Enter a number: ")
fmt.Scan(&number)
// Call the function and print the lucky numbers
fmt.Print("\nLucky numbers till ", number, " are: ")
lucky_number(number)
}
/*
Sample I/O:
Enter a number: 100
Lucky numbers till 100 are: 1 3 7 9 13 15 21 25 31 33 37 43 49 51 63 67 69 73 75 79 87 93 99
Time complexity - O(k * n)
Space complexity - O(n)
here n is the input number and k is a constant.
*/