Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: In-Person
int getKthMagicNumber (int k) {
queue<int> q2, q3, q5 ;
int val = 1, minVal ;
if (k <= 0)
return 0 ;
q2.push (2) ;
q3.push (3) ;
q5.push (5) ;
for ( --k ; k > 0 ; -- k ) {
minVal = min (q2.front(), min (q3.front(), q5.front())) ;
if ( minVal == q5.front() ) {
q5.pop () ;
} else {
if ( minVal == q3.front() ) {
q3.pop () ;
} else {
q2.pop () ;
q2.push (minVal*2) ;
}
q3.push (minVal*3) ;
}
q5.push (minVal*5);
}
return minVal ;
}
<?php
for($i=1;$i<n;$i++)
{
$temp=i;
while($i%2==0)
{
$temp=i/2;
if($temp==1)
break;
}
if($temp==1 || $temp%3==0 || $temp%5==0)
echo $i." ";
}
?>
void foo(int n)
{
for (int i =0; i <=n ; i++)
{
int counter = 0;
if (i % 2 == 0)
{
++counter;
}
if ( i % 3 == 0)
{
++counter;
}
if (i % 5 == 0)
{
++counter;
}
if (counter >= 1)
{
if (i % 7 != 0)
printf("%d \n", i);
}
counter = 0;
}
}
int main()
{
int n;
scanf("%d",&n);
foo(n);
return 0;
}
Use DP.
Complete working code: ideone.com/qz4Py
- Aashish July 24, 2012It prints first n ugly numbers.
Note: I have also considered 1 as part of the ugly number series.