Sereja and GCD 2

本文探讨了一种算法问题,即计算满足特定条件的数组数量。具体来说,对于给定的整数N和M,需要找出所有长度为N的数组A(每个元素Ai介于1到M之间),使得任意两个不同位置的元素的最大公约数都等于1。文章提供了一个使用递归搜索的方法来解决该问题,并通过预计算最大公约数来优化效率。

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

下面的做法会超时

Read problems statements in Mandarin Chinese, Russian and Vietnamese as well.

Sereja asks you to find out number of arrays A of size N, i.e. A1, A2, ..., AN (1 ≤ Ai ≤ M), such that for each pair i, j (1 ≤ i < j ≤ N) gcd(Ai, Aj) = 1.

As the answer could be large, print it modulo 109 + 7 (1000000007).

Input

First line of the input contain an integer T - number of test cases.

T tests follow. First line of each test case contain two space separated integers N, M.

Output

For each test case output required answer modulo 10^9 + 7.

Constraints

  • 1T 10
  • 1N 105
  • 1M 100

Subtasks

  • Subtask #1: (10 points, TL = 5 secs) 1N, M 10
  • Subtask #2: (25 points, TL = 5 secs) 1N 100
  • Subtask #3: (65 points, TL = 5 secs) original

Example

Input:
2
1 1
3 3

Output:
1
13
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll mod=1e9+7;
int gcd[110][110];
int ggcd(int a,int b){
    if(b==0)return a;
    return ggcd(b,a%b);
}
const int N=1e5+10;

int m,n;
int ans;
int val[N];

void dfs(int cur){
    if(cur==n){
        ans++;
        return ;
    }
    for(int i=1;i<=m;i++){
        if(cur==0){
            val[cur]=i;
            dfs(cur+1);
        }else{
            val[cur]=i;
            bool flag=true;
            for(int j=0;j<cur;j++)
            if(gcd[val[cur]][val[j]]!=1){
                flag=false;
                break;
            }
            if(flag)dfs(cur+1);
        }
    }
}


int main(){
    for(int i=1;i<=100;i++)
    for(int j=i;j<=100;j++)
    gcd[i][j]=gcd[j][i]=ggcd(i,j);
    int t;
    cin>>t;
    while(t--){
        cin>>n>>m;
        ans=0;
        dfs(0);
        cout<<ans<<endl;
    }
}



 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值