UVA 136 Ugly Numbers
原題代號:UVA 136
原題鏈接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&page=show_problem&problem=72
題目原題:
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
There is no input to this program.
Output
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>.
題目不難就是輸出語句沒看懂。。。提交時候錯了好多次。。。
題目大意:定義一種類型的數字叫做“醜數”他僅僅由2,3,5這三個質數構成的數叫做醜數,並且額外定義1也是醜數,所以醜數前11項是:1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 讓你求第1500個醜數的值。
題目理解:對於每一個質數2 3 5,我們都要找到對應的之前已經計算出的最小的醜數使之乘以這個質數後大於當前的醜數,然後再從這三個裏取最小的那個,我們記錄三個數i,j,k,分別保存對應的質數計算到哪個下標了,然後更新所有質數對應的下標,使之乘積大於當前的醜數。
AC代碼:
# include <stdio.h> # include <string.h> # include <stdlib.h> # include <iostream> # include <fstream> # include <vector> # include <queue> # include <stack> # include <map> # include <math.h> # include <algorithm> using namespace std; # define pi acos(-1.0) # define mem(a,b) memset(a,b,sizeof(a)) # define FOR(i,a,n) for(int i=a; i<=n; ++i) # define For(i,n,a) for(int i=n; i>=a; --i) # define FO(i,a,n) for(int i=a; i<n; ++i) # define Fo(i,n,a) for(int i=n; i>a ;--i) typedef long long LL; typedef unsigned long long ULL; int a[1505]={0,1}; int main() { int i=1,j=1,k=1,ans=1; for(int t=2;t<=1500;t++) { a[t]=min(min(2*a[i],3*a[j]),5*a[k]); if(2*a[i]==a[t])i++; if(3*a[j]==a[t])j++; if(5*a[k]==a[t])k++; } int n; printf("The 1500‘th ugly number is %d.\n",a[1500]); return 0; }
UVA 136 Ugly Numbers