Sunday, January 18, 2009

Lucky Number

Prob: All the numbers from 1 to infinity are written in sequence:
1,2,3,4,5,6,7,8,9,10,11,12,13,14.....
in the first iteration, every second number is removed, leaving:
1,3,5,7,9,11,13....
in the second iteration, every third number in the above sequence is
removed, thus leaving: 1,3,7,9,13....
in the third iteration, every fourth number is removed, leaving:
1,3,7,13....
like this the process goes on indefinitely.
the numbers which are, thus, left are called lucky numbers.

Write an algorithm to verify whether given a number n(can be as big as 18
digits)lucky number or not.

Sol: First n will be the nth number in the sequence. After each iteration
(intially i=2) the new position of n is calculated as n=n- (n/i) and if
n%i then u stop. this goes on until n less than i.
if n becomes less than i then n is lucky.

C-Version:

void luckyOrNot(long int n){
long int n2 = n;
int i= 2;
while(n2>=i){
if(n2%i == 0){
printf("%ld got unlucky when i was %d\n", n, i);
break;
}
n2 = n2 - (n2/i);
i++;
}
if(n2<i){
printf("%ld is lucky\n", n);
}
}

No comments: