ZCMU—1570

1570: Palindromic Numbers

Time Limit: 1 Sec   Memory Limit: 128 MB
Submit: 102   Solved: 7
[ Submit][ Status][ Web Board]

Description

    • Johnny has figured out that there are some numbers which have an interesting property: they are the same when read from left to right, and from right to left. For example, 5115 and 929 are such numbers, while 31 and 125 are not. Johnny calls such numbers palindromic numbers.

      After a while, Johnny has realized that his definition of palindromic numbers is not really precise. Whether a number is palindromic or not depends on the base in which the number is written. For example, 21 is not palindromic in base 10 but it is palindromic in base 2 (because 21 = 101012).

      Johnny finds it interesting that any number becomes palindromic when it is written in an appropriate base.

      Given a number N, write a program to help Johnny compute the smallest base B such that N is palindromic when written in base B.

Input

  • The first line contains t, the number of test cases (about 1000). Then t test cases follow.

    Each test case consists of a number N written in one line (1 <= N <= 1010).

Output

For each given number N, print a line containing the smallest base B such that N is palindromic in base B.

Sample Input

3
1
4
21

Sample Output

2
3
2

【分析】

题意:给出一个数N,求一个最小的ans使得N在ans进制下是回文数
首先考虑爆搜....然而10^10爆搜是肯定不行的,那么先考虑一个肯定是答案的数字是多少,显然我们可以发现一件事,如果当前数字为N,那么N可以表示成m*n的形式,也就是N=m*n,那么我们可以发现,当N为(n-1)进制或者(m-1)进制时,N一定为回文数
证明:首先假设m<n,因为题目要求的是最小的进制数,所以肯定取小的数作为上限答案
1.N=m*n=m*(n-1)+m
2.N%(n-1)=(m*(n-1)+m)%(n-1)=m%(n-1)=m
3.N/(n-1)取整=m
4.m%(n-1)=m
5.所以N在(n-1)进制下答案就是mm一定是回文
所以这样就可以得出上限是什么,所以我们只需要判断到sqrt(n)的地方,那么10^10开根号之后也只有10W次的check,每次check速度基本为常数忽略不计,那么时间复杂度为O(Tsqrt(n))
另外我们可以发现,当数字较小时,比如4,用这个判断方法会有问题,但是其实不用想那么多,既然对于10W次的运算都不会有问题,那么我们考虑当n<10000时不开sqrt,爆搜答案是什么即可
【代码】
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath> 
using namespace std;
int f[100000];
int check(int m,long long x)
{
	int len=0;
	while (x)
	{
		f[len++]=x%m;
		x/=m;
	}
	for (int i=0;i<len/2;i++)
		if (f[i]!=f[len-i-1])
			return 0;
	return 1;
}

int main()
{
	int T_T;scanf("%d",&T_T);
	while (T_T--)
	{
		long long n;scanf("%lld",&n);
		if (n==1)
		{
			printf("2\n");
			continue;
		}
		int len=sqrt(n);
		if (n<10000) len=n;	
		for (int i=2;i<=len;i++)
			if (check(i,n))
			{
				printf("%d\n",i);
				goto out;
			}
		len=sqrt(n);
		for (int i=len;i>=1;i--)
			if (n%i==0)
			{
				printf("%lld\n",n/i-1);
				break;
			}
		out:;
	}
	return 0;
} 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值