Codeforces Round #653 (Div. 3) B. Multiply by 2, divide by 6 (数学)

-
题意:有一个数\(n\),每次操作可以使\(n*=2\)或\(n/=6\)(如果能被整除),求最少操作次数使得\(n=1\),如果不满足,输出\(-1\).
-
题解:我们只要看\(n\)的质因子即可,如果要满足条件,那么它的质因子只能含有\(2\)和\(3\),并且\(2\)的次数不大于\(3\)的次数.直接去找\(2\)和\(3\)的次数即可.
(写了个质因数分解被hack了,呜呜呜) -
代码:
int t; int n; int main() { ios::sync_with_stdio(false);cin.tie(0); cin>>t; while(t--){ cin>>n; int cnt1=0; int cnt2=0; while(n%2==0){ n/=2; cnt1++; } while(n%3==0){ n/=3; cnt2++; } if(n!=1 || cnt1>cnt2){ cout<<-1<<endl; } else{ cout<<2*cnt2-cnt1<<endl; } } return 0; }
𝓐𝓬𝓱𝓲𝓮𝓿𝓮𝓶𝓮𝓷𝓽 𝓹𝓻𝓸𝓿𝓲𝓭𝓮𝓼 𝓽𝓱𝓮 𝓸𝓷𝓵𝔂 𝓻𝓮𝓪𝓵
𝓹𝓵𝓮𝓪𝓼𝓾𝓻𝓮 𝓲𝓷 𝓵𝓲𝓯𝓮

浙公网安备 33010602011771号