codefoces-A. Divide it!

题目链接
You are given an integer n.

You can perform any of the following operations with this number an arbitrary (possibly, zero) number of times:

Replace n with n2 if n is divisible by 2;
Replace n with 2n3 if n is divisible by 3;
Replace n with 4n5 if n is divisible by 5.
For example, you can replace 30 with 15 using the first operation, with 20 using the second operation or with 24 using the third operation.

Your task is to find the minimum number of moves required to obtain 1 from n or say that it is impossible to do it.

You have to answer q independent queries.

Input
The first line of the input contains one integer q (1≤q≤1000) — the number of queries.

The next q lines contain the queries. For each query you are given the integer number n (1≤n≤1018).

Output
Print the answer for each query on a new line. If it is impossible to obtain 1 from n, print -1. Otherwise, print the minimum number of moves required to do it.

Example
input
7
1
10
25
30
14
27
1000000000000000000
output
0
4
6
6
-1
6
72

题意:
就是给你一个整数,有三种操作:
如果n可被2除,n变为n/2;
如果n2可被3除,则将n替换为2n/3;
如果n4可被5除,则将n替换为4n/5。
你可以执行任何操作使得最后变为1即可;
找到最小的一个方式使得操作步数最小;

解题策略: 贪心 贪心策略能使一个数变得更小就变更小;
也就是说是能执行第一种操作就执行第一种,能执行第二种就执行第二种操作,最后执行第三种,因为第一种比第二种和第三种改变的值更小;

#include<stdio.h>
#include<algorithm>
#include<iostream>
#define ll long long
using namespace std;
int main()
{
    int t;
    scanf("%d",&t);
    ll n;
    while(t--)
    {
        scanf("%lld",&n);
        if(n==1){
            printf("0\n");
        }
        else if((n%2==0)||(n*2%3==0)||(n*4%5==0))
        {
            //cout<<"sd "<<endl;
            int sum=0;
            int flag=1;
            while(n)
            {
                 if(n%2==0)//贪心 只要能执行操作1 就先 执行操作1
                 {
                     n/=2;
                     sum++;
                 }
                 else if((n*2)%3==0)//贪心 只要能执行操作2  就先 执行操作2
                 {
                     n=n*2/3;
                     sum++;
                 }
                 else if(n*4%5==0)//贪心 只要能执行操作3 就执行操作3
                 {
                     n=n*4/5;
                     sum++;
                 }
                 if(n==1)//结束
                 {
                     break;
                 }
                 if(n!=1&&n*4%5!=0&&n%2!=0&&n*2%3!=0)//如果循环不满足三种操作就结束
                 {
                     flag=0;
                     break;
                 }
            }
            if(flag)
            printf("%d\n",sum);
            else
                printf("-1\n");
        }
        else
            printf("-1\n");
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值