HDU 5505 GT and numbers【思维+GCD】

本文探讨了GTandnumbers问题的解决策略,该问题要求计算通过特定操作使数字N至少等于M所需的步骤数。文章详细介绍了如何使用最大公约数(GCD)进行优化,并分享了解题过程中的挑战及心得。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GT and numbers

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1839    Accepted Submission(s): 500


Problem Description
You are given two numbers N and M.

Every step you can get a new N in the way that multiply N by a factor of N.

Work out how many steps can N be equal to M at least.

If N can't be to M forever,print 1.
 

Input
In the first line there is a number T.T is the test number.

In the next T lines there are two numbers N and M.

T10001N1000000,1M263.

Be careful to the range of M.

You'd better print the enter in the last line when you hack others.

You'd better not print space in the last of each line when you hack others.
 

Output
For each test case,output an answer.
 

Sample Input
3 1 1 1 2 2 4
 

Sample Output
0 -1 1

     一碰到这题就不会了,先写感觉没有错,最后发现题意没理解对,N是一直变得,因子也会变,写了又超时,又忘了优化一下GCD,GCD竟然也会超时,搜一下简化版的GCD,提交一下又MLE,这真是一道好题,那一点想不到都不行,必须优化到最优的形式,还是多思考吧;


#include<cstdio>

typedef unsigned long long LL;

LL GCD(LL a,LL b)
{
	return !b?a:GCD(b,a%b);
} 
int main()
{
	LL T,M,N,i;
	scanf("%llu",&T);
	while(T--)
	{
		bool falg=true; LL cnt=0;
		scanf("%llu %llu",&N,&M);
	    if(N>M||M%N) {
	    	falg=false; 
		}
		else if(N==M) falg=true;
		else {
		     while(N<M)
		     {
		     	 LL tem=GCD(M/N,N);
		     	 if(tem==1)
		     	 {
		     	    falg=false; break;
				 }
				N*=tem; ++cnt; 
			 }
		}
		if(falg) printf("%llu\n",cnt);
		else printf("-1\n");
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值