C - Reading comprehension 二分法 求等比数列前N项和
Read the program below carefully then answer the question.
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include<iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include<vector>
const int MAX=100000*2;
const int INF=1e9;
int main()
{
int n,m,ans,i;
while(scanf("%d%d",&n,&m)!=EOF)
{
ans=0;
for(i=1;i<=n;i++)
{
if(i&1)ans=(ans*2+1)%m;
else ans=ans*2%m;
}
printf("%d\n",ans);
}
return 0;
}
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include<iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
#include<vector>
const int MAX=100000*2;
const int INF=1e9;
int main()
{
int n,m,ans,i;
while(scanf("%d%d",&n,&m)!=EOF)
{
ans=0;
for(i=1;i<=n;i++)
{
if(i&1)ans=(ans*2+1)%m;
else ans=ans*2%m;
}
printf("%d\n",ans);
}
return 0;
}
InputMulti test cases,each line will contain two integers n and m. Process to end of file.
TechnicalSpecification
1<=n, m <= 1000000000OutputFor each case,output an integer,represents the output of above program.Sample Input
1 10 3 100
Sample Output
1 5
等比数列二分求和:
(1)当时,
(2)当时,那么有
(3)当时,那么有
#include<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<sstream> #include<algorithm> #include<queue> #include<deque> #include<iomanip> #include<vector> #include<cmath> #include<map> #include<stack> #include<set> #include<fstream> #include<memory> #include<list> #include<string> using namespace std; typedef long long LL; typedef unsigned long long ULL; #define MAXN 18 #define N 33 #define MOD 10000007 #define INF 1000000009 const double eps = 1e-9; const double PI = acos(-1.0); LL n, m, ans; /* 等比数列二分求和 */ LL fpow(LL a, LL b) { LL ret = 1, tmp = a; while (b != 0) { if (b & 1) ret = ret*tmp%m; tmp = tmp*tmp%m; b /= 2; } return ret%m; } LL sum(LL a, LL k) { LL t, cur; if (k == 1) return a; else if (k % 2 == 1) { t = sum(a, k / 2),cur = fpow(a, k / 2 + 1); t = (t + t * cur%m) % m; t = (t + cur) % m; } else { t = sum(a, k / 2), cur = fpow(a, k / 2); t = (t + t * cur % m) % m; } return t; } LL solve(LL num) { if (num == 0) return 1; else return (1 + sum(4, num)) % m; } int main() { while (cin >> n >> m) { if (n & 1) cout << solve(n/2)%m << endl; else cout << solve((n - 1)/2)*2%m << endl; } }