描述
传送门:我是传送门
Alice, a student of grade 66, is thinking about an Olympian Math problem, but she feels so despair that she cries. And her classmate, Bob, has no idea about the problem. Thus he wants you to help him. The problem is:
We denote k!k!:
k!=1×2×⋯×(k−1)×k
We denote SS:
S=1×1!+2×2!+⋯+(n−1)×(n−1)!
Then SS module nn is __
You are given an integer nn.
You have to calculate SS modulo nn.
输入
The first line contains an integer T(T≤1000)T(T≤1000), denoting the number of test cases.
For each test case, there is a line which has an integer nn.
It is guaranteed that 2≤n≤10^18.
输出
For each test case, print an integer SS modulo nn.
样例
输入
2
2
3
输出
1
2
Note
The first test is: S=1×1!=1, and 1 modulo 2 is 1.
The second test is: S=1×1!+2×2!=5 , and 5 modulo 3 is 2.
证明
首先我们知道
- n!=n∗(n−1)! and n!(modn)=0
- x−0=xx−0=x
下面开始
证明(xjb推)
1×1!+2×2!+…+(n−1)×(n−1)=1×1!+2×2!+…+(n−1)×(n−1)−n!取出最后两项(n−1)×(n−1)!−n!, 因为n!=n×(n−1)!n!=n×(n−1)! ,因此可以将最后两项写为(n−1−n)×(n−1)!=(−1)×(n−1)!
现在原式变为1×1!+2×2!+…+(n−2)×(n−2)!−(n−1)!,再次取出最后两项(n−2)×(n−2)!−(n−1)!,此式可化为(n−2)×(n−2)!−(n−1)×(n−2)!=(n−2−n+1)×(n−2)!
上式最终为(−1)∗(n−2)!(−1)∗(n−2)!
原式变为1×1!+2×2!+…+(n−3)×(n−3)!−(n−2)!最终会变为(−1)×1!=−1
(−1)(modn)=n−1
代码
1 #include <cstdio> 2 using namespace std; 3 int main() 4 { 5 long long T,n; 6 scanf("%lld",&T); 7 while (T--) 8 { 9 scanf("%lld", &n); 10 printf("%lld\n", n - 1); 11 } 12 return 0; 13 }