问 (1+2√)n 能否分解成 m−−√+(√m−1) 的形式
如果可以 输出 m MOD (109+7) 否则 输出 no
Input
一行,一个数
n
。
Output
一行,如果不存在
m
输出
Input示例
2
Output示例
9
解题思路:
首先这个题目不存在没有解的情况证明如下:
考虑构造对偶式:
(1+2√)n=a+b∗2√——(1)
(1−2√)n=a−b∗2√——(2)
(1) (2) 两式相乘得到:
(−1)n=a2−2∗b2
于是 当n为偶数:有
1=a2−2∗b2
若m为a2 则 m−1=a2−1=2b2
sqrt(m)+sqrt(m−1)=a+b∗sqrt(2)
当n为奇数 同理可得 m=a2+1
现在我们就来看 a 到底是什么了,通过观察和打表找规律,发现一个递推式:
那么现在我们就可以通过矩阵快速幂来实现了,如果不会矩阵快速幂的同学可以看这篇
博客:传送门
My Code:
/**
2016 - 08 - 27 下午
Author: ITAK
Motto:
今日的我要超越昨日的我,明日的我要胜过今日的我,
以创作出更好的代码为目标,不断地超越自己。
**/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <vector>
#include <queue>
#include <algorithm>
#include <set>
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const int INF = 1e9+5;
const int MAXN = 2;
const LL MOD = 1e9+7;
const double eps = 1e-7;
const double PI = acos(-1);
using namespace std;
LL Scan_LL()///输入外挂
{
LL res=0,ch,flag=0;
if((ch=getchar())=='-')
flag=1;
else if(ch>='0'&&ch<='9')
res=ch-'0';
while((ch=getchar())>='0'&&ch<='9')
res=res*10+ch-'0';
return flag?-res:res;
}
int Scan_Int()///输入外挂
{
int res=0,ch,flag=0;
if((ch=getchar())=='-')
flag=1;
else if(ch>='0'&&ch<='9')
res=ch-'0';
while((ch=getchar())>='0'&&ch<='9')
res=res*10+ch-'0';
return flag?-res:res;
}
void Out(LL a)///输出外挂
{
if(a>9)
Out(a/10);
putchar(a%10+'0');
}
typedef struct
{
LL mat[MAXN][MAXN];
} Matrix;
LL c;
///求得的矩阵
Matrix p = {2, 1,
1, 0,
};
///单位矩阵
Matrix I = {1, 0,
0, 1,
};
///矩阵乘法
Matrix Mul_Matrix(Matrix a, Matrix b)
{
Matrix c;
for(int i=0; i<MAXN; i++)
{
for(int j=0; j<MAXN; j++)
{
c.mat[i][j] = 0;
for(int k=0; k<MAXN; k++)
{
c.mat[i][j] += (a.mat[i][k] * b.mat[k][j]) % MOD;
c.mat[i][j] %= MOD;
}
}
}
return c;
}
///矩阵的快速幂
Matrix quick_Mod_Matrix(LL m)
{
Matrix ans = I, b = p;
while(m)
{
if(m & 1)
ans = Mul_Matrix(ans, b);
m>>=1;
b = Mul_Matrix(b, b);
}
return ans;
}
///普通的快速幂
LL quick_Mod(LL a, LL b)
{
LL ans = 1;
while(b)
{
if(b & 1)
ans = (ans * a) % MOD;
b>>=1;
a = (a * a) % MOD;
}
return ans;
}
int main()
{
LL n;
while(cin>>n)
{
if(n == 0)
{
puts("1");
continue;
}
if(n == 1)
{
puts("2");
continue;
}
if(n == 2)
{
puts("9");
continue;
}
Matrix tmp = quick_Mod_Matrix(n-2);
LL ans = 0;
ans = 3*tmp.mat[0][0] + tmp.mat[1][0];
ans %= MOD;
ans = ans*ans;
ans = (ans%MOD+MOD)%MOD;
if(n%2 == 1)
cout<<(ans+1)%MOD<<endl;
else
cout<<ans<<endl;
}
return 0;
}