C. Finite or not?
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given several queries. Each query consists of three integers pp, qq and bb. You need to answer whether the result of p/qp/q in notation with base bb is a finite fraction.
A fraction in notation with base bb is finite if it contains finite number of numerals after the decimal point. It is also possible that a fraction has zero numerals after the decimal point.
Input
The first line contains a single integer nn (1≤n≤1051≤n≤105) — the number of queries.
Next nn lines contain queries, one per line. Each line contains three integers pp, qq, and bb (0≤p≤10180≤p≤1018, 1≤q≤10181≤q≤1018, 2≤b≤10182≤b≤1018). All numbers are given in notation with base 1010.
Output
For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.
Examples
input Copy
2
6 12 10
4 3 10
output Copy
Finite
Infinite
input Copy
4
1 1 2
9 36 2
4 12 3
3 5 4
output Copy
Finite
Finite
Finite
Infinite
题目大概:
问p/q的值,转化为b进制的数后,是否为有限小数,或无限小数。
思路:
首先是用gcd,让p/q约分到最简,然后p对于答案来说是没有影响的,因为它在分母上。
至于1/q,则用十进制小数转化为b进制的方法,直接每次乘b取整,余的小数继续下去。
这样分析一下,只有当q和b不互质之前,小数部分为1,才能是有限小数,否则是无限的。
#include <bits/stdc++.h>
using namespace std;
long long gcd(long long m, long long n)
{
while(m>0)
{
long long c = n % m;
n = m;
m = c;
}
return n;
}
int main()
{
long long t;
scanf("%I64d",&t);
while(t--)
{
long long p,q,b;
scanf("%I64d%I64d%I64d",&p,&q,&b);
long long di=gcd(p,q);
if(di!=1)
{
p/=di;
q/=di;
}
long long ans=b;
while(ans!=1)
{
while(q%ans==0)q/=ans;
ans=gcd(q,b);
}
if(q==1)
{
printf("Finite\n");
}
else printf("Infinite\n");
}
return 0;
}