Finite or not?(详细题解)

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 (1n1051≤n≤105) — the number of queries.

Next nn lines contain queries, one per line. Each line contains three integers pp, qq, and bb (0p10180≤p≤1018, 1q10181≤q≤1018, 2b10182≤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
Note

612=12=0,510612=12=0,510

43=1,(3)1043=1,(3)10

936=14=0,012936=14=0,012

412=13=0,13

首先考虑我们熟悉的十进制,若a/b为有限小数,则将a/b约分后,得互质的a1/b1。要a1/b1为有限小数,其充要条件为 1/b1为有限小数。十进制时,我们其实是将1*10/b.得到的结果再乘10除以b,经过有限次的循环后,总能bn%10=0。

也就是说 存在n,10^n%b1=0。也就是说 10^n存在b1的所有因子(2,5)。那么在x进制下,就是存在n,x^n%b1=0--->x^n存在b1的所有因子!

这就转化成了一道数论题。

我们考虑用欧几里得算法解(因为数据太大了,直接乘会爆)。我们设约分后的值分别为a1,b1,进制为x。那么求解x^n是否包含b1的所有因子,我们先求x,b1的gcd,然后将x/gcd,b1=gcd。(因为b1/gcd的那一部分与x绝对是互质的,是没有用的,所有我们直接将其除掉)。如此循环,看b1最终能否等于1就好了。

AC代码:

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
    int n;
    scanf("%d",&n);
    while(n--)
    {
        ll p,q,b;
        scanf("%I64d%I64d%I64d",&p,&q,&b);
        ll g=__gcd(p,q);
        p/=g;
        q/=g;
        if(q==1||p==0)
        {
            printf("Finite
");
        }
        else
        {
            while(q!=1&&b!=1)
            {
                b=__gcd(b,q);
                q/=b;
            }
            if(q==1)
            {
                printf("Finite
");
            }
            else
            {
                printf("Infinite
");
            }
        }
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/zyf3855923/p/9050040.html