Problem : Ugly Numbers
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ...
shows the first 11 ugly numbers. By convention, 1 is included.
Write a program to find and print the 1500'th ugly number.
Input and Output
There is no input to this program. Output should consist of a single line as shown below, with <number> replaced by the number computed.
Sample output
The 1500'th ugly number is <number>.
My accepted code is given below:
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long a,b,c,n,i,ar[1599]={0},x,y,z;
a=b=c=n=1;
ar[1]=1;
while(n!=1501)
{
//cout<<ar[n]<<endl;
x=2*ar[a];
y=3*ar[b];
z=5*ar[c];
ar[++n]=min(x,min(y,z));
if(ar[n]==x)
a++;
if(ar[n]==y)
b++;
if(ar[n]==z)
c++;
}
cout<<"The 1500'th ugly number is "<<ar[1500]<<"."<<endl;
}
Ugly numbers are numbers whose only prime factors are 2, 3 or 5. The sequence
1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ...
shows the first 11 ugly numbers. By convention, 1 is included.
Write a program to find and print the 1500'th ugly number.
Input and Output
There is no input to this program. Output should consist of a single line as shown below, with <number> replaced by the number computed.
Sample output
The 1500'th ugly number is <number>.
My accepted code is given below:
#include<bits/stdc++.h>
using namespace std;
int main()
{
long long a,b,c,n,i,ar[1599]={0},x,y,z;
a=b=c=n=1;
ar[1]=1;
while(n!=1501)
{
//cout<<ar[n]<<endl;
x=2*ar[a];
y=3*ar[b];
z=5*ar[c];
ar[++n]=min(x,min(y,z));
if(ar[n]==x)
a++;
if(ar[n]==y)
b++;
if(ar[n]==z)
c++;
}
cout<<"The 1500'th ugly number is "<<ar[1500]<<"."<<endl;
}
please add logical idea with the solution .It can help us to understand the problem fast.
ReplyDeleteThank your solution, i was build a new code with same algorithm and it accepted
ReplyDelete#include
#define int long long
using namespace std;
int32_t main(){
set myset;
myset.insert(1);
auto it= myset.begin();
int cnt= 0;
while(++cnt < 1500){
int x= (*it)*2;
int y= (*it)*3;
int z= (*it)*5;
myset.insert(x);
myset.insert(y);
myset.insert(z);
it++;
}
cout<<"The 1500'th ugly number is "<<(*it)<<".\n";
}