1570: Palindromic Numbers
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 110 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
Sample Output
#include<algorithm>
#include<string.h>
#include<stdio.h>
using namespace std;
const int MOD=1000000007;
int pan(int n,int k)
{
int a[35]={0};
int r=0;
while(n)
{
a[r++]=n%k;
n=n/k;
}
int i;
for(i=0;i<=(r-1)/2;i++)
{
if(a[i]!=a[r-1-i])
{
break;
}
}
if(i>(r-1)/2)
return 1;
else
return 0;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
long long n;
scanf("%lld",&n);
if(n==1)
{
printf("2\n");
continue;
}
if(n==2)
{
printf("3\n");
continue;
}
for(int i=2;i<=n;i++)
{
if(pan(n,i))
{
printf("%d\n",i);
break;
}
}
}
return 0;
}
#include<algorithm>
#include<string.h>
#include<stdio.h>
#include<math.h>
#include<cmath>
using namespace std;;
int a[100000];
int pan(long long n,int k)
{
int r=0;
while(n)
{
a[r++]=n%k;
n=n/k;
}
int i;
for(i=0;i<r/2;i++)
if(a[i]!=a[r-1-i])
return 0;
return 1;
}
int main()
{
int t;
scanf("%d",&t);
while(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(pan(n,i))
{
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;
}