列表

详情


NC25999. Icebound and Sequence

描述

Icebound hates math. But Imp loves math. One day, Imp gave icebound a problem.

The problem is as follows.



For given q,n,p, you need to help icebound to calculate the value of S.

输入描述

The first line contains an integer T, denoting the number of test cases.
The next T lines, each line contains three integers q,n,p, separated by spaces.
,

输出描述

For each test case, you need to output a single line with the integer S.

示例1

输入:

2
2 3 100
511 4 520

输出:

14
184

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++14(g++5.4) 解法, 执行用时: 5ms, 内存消耗: 612K, 提交时间: 2019-05-25 12:58:07

#include <iostream>
using namespace std;
int t;
int n,q,p;
int qpow(int a,int b){
	int c=1;
	while (b){
		if (b&1)
			c=1ll*a*c%p;
		b>>=1;
		a=1ll*a*a%p;
	}
	return c;
}
int solve(int l){
	if (l==1) return q;
	int mid=l>>1;
	int p1=solve(mid);
	if (l&1)
		return (1ll*p1+1ll*qpow(q,mid)*p1%p+qpow(q,l))%p;
	return (1ll*p1+1ll*qpow(q,mid)*p1%p)%p;
}
int main(){
	cin >> t;
	while (t--){
		cin >> q >> n >> p;
		cout << solve(n) << '\n';
	}
}

C++(clang++11) 解法, 执行用时: 10ms, 内存消耗: 504K, 提交时间: 2021-05-01 15:44:40

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n,q,mod;
ll qpow(ll a,ll b){
	ll res=1;
	while(b){
		if(b&1) res=res*a%mod;
		a=a*a%mod;
		b>>=1;
	}
	return res;
}
ll sum(ll p,ll k){
	if(k==1) return p%mod;
	if(k%2==1) return (sum(p,k-1)  +qpow(p,k))%mod;
	return (1+qpow(p,k/2)) * sum(p,k/2) %mod; 
}
int main(){
	int t;
	scanf("%d",&t);
	while(t--){
		cin>>q>>n>>mod;
		cout<<sum(q,n) %mod<<endl;
	}
}

Python3(3.9) 解法, 执行用时: 20ms, 内存消耗: 2680K, 提交时间: 2020-10-31 15:36:11

T = int(input())
for i in range(T):
    q, n, p = map(int, input().split())
    mod = (q - 1) * p
    ans = (q * (pow(q, n, mod) - 1 + mod) % mod) // (q - 1)
    print(ans)

上一题