Problem:
Assume given sequence :
2,3,4,5,6,8,9,10,12,15...
All these numbers are multiples of either 2 , 3, or 5 (and no other numbers).
Find the nth element of this sequence. (This is the interview question in flipkart)
Solution:
This can be thought in recursive terms. But to begin with, we can clearly see, 2.5=10 is part of series, but 2.7=14 is not part of series. So, while generation of numbers we have to make sure that divisor is not part of numbers like 7,11,13 etc.
Java code
Thanks
Assume given sequence :
2,3,4,5,6,8,9,10,12,15...
All these numbers are multiples of either 2 , 3, or 5 (and no other numbers).
Find the nth element of this sequence. (This is the interview question in flipkart)
Solution:
This can be thought in recursive terms. But to begin with, we can clearly see, 2.5=10 is part of series, but 2.7=14 is not part of series. So, while generation of numbers we have to make sure that divisor is not part of numbers like 7,11,13 etc.
Java code
public int GetNumberFromSequence(int n) { if(n==1) return 2; if(n>1) for(int i=1;;i++) { int possibleNumber=GetNumberFromSequence(n-1)+i; if(IsAllowedNumber(possibleNumber)) return possibleNumber; else continue; } } public bool IsAllowedNumber(int possibleNumber) { for(int n: primesExcept_2_3_5 ) if(possibleNumber%n == 0) return false; else if(n>possibleNumber) return true; }
Thanks
0 comments:
Post a Comment