Finite or not?

本文介绍了一个算法问题,即如何判断一个分数在特定进制下能否表示为有限小数。通过约分和检查分母质因数的方式,文章提供了一种有效的解决方法。

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

You are given several queries. Each query consists of three integers p, q and b. You need to answer whether the result of p/q in notation with base b

is a finite fraction.

A fraction in notation with base b

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 n

(1≤n≤105

) — the number of queries.

Next n

lines contain queries, one per line. Each line contains three integers p, q, and b (0≤p≤1018, 1≤q≤1018, 2≤b≤1018). All numbers are given in notation with base 10

.

Output

For each question, in a separate line, print Finite if the fraction is finite and Infinite otherwise.

Examples

Input

2
6 12 10
4 3 10

Output

Finite
Infinite

Input

4
1 1 2
9 36 2
4 12 3
3 5 4

Output

Finite
Finite
Finite
Infinite

 

 

题目大意:

给定三个数p, q, b;要求你判断p / q在b进制下是否能用有限的小数表示

解题思路:必须要先约分,然后判断q是否可以由b的因数构成,如果可以则YES意,否则就NO。

简单阐述一下原理:就拿二进制来说吧,1/4,也就是0.25要化成二进制需要乘2取整数部分。给大家演示一下,0.25 × 2 = 0.5,取出0,余下0.5,然后0.5 × 2 = 1;取出1,余下0,完毕。化成二进制也就是0.01(2)。

其他进制也类似,总的来说,p / q *b *b.....之后能得到一个整数,也就是若干个b可以约掉p那就行;

废话少说,上代码:

#include <iostream>
#include <set>
#include <algorithm>
#include <cstdio>
using namespace std;


long long gcd(long long a, long long b)
{
  if(b == 0)
    return a;
  else
    return gcd(b, a % b);
}

int main()
{
    long long n;
    scanf("%lld", &n);
    long long p, q, b;
    while(n --)
    {
      scanf("%lld%lld%lld", &p, &q, &b);
      long long t = gcd(p, q);
      q /= t;
      while(q != 1)
      {
        long long s = gcd(q, b);
        if(s == 1)
          break;
        while(q % s == 0)
           q /= s;
      }
      if(q == 1)
      {
        cout << "Finite" << endl;
      }
      else
        cout << "Infinite" << endl;
    }

    return 0;
}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值