大数取余数-----x的y次方取余数
发布时间:2021-01-21 20:37:07 所属栏目:大数据 来源:网络整理
导读:大数取余数--- 题目描述: 输入一个位数不超过10^6的整数a,求a%5并输出 //此题肯定不能用long,int表示要输入的这个整数,这两种类型表示的范围没有题目要求的那么大;可用string #includeiostream#includestringusing namespace std;int main(){string str
|
大数取余数---题目描述:
#include<iostream>
#include<string>
using namespace std;
int main(){
string str;
cin>>str;
int i;
int rem=0;
for(i=0;i<str.length();i++){
rem=rem*10+str[i]-'0';
rem=rem%5;//这里对其他数取余的话,5可以换成其他的数
}
cout<<rem<<endl;
}
x的y次方取余数Google Round B https://code.google.com/codejam/contest/5254487/dashboard#s=p1 只会做small practice。。。 涉及到x的y次方,对mod取余数,如下。 /***
*
* @param x
* @param y
* @param mod
* @return
*/
public static long power(long x,long y,long mod) {
long t = 1;
while (y > 0) {
if (y % 2 == 1) {
y -= 1;
t = t*x%mod;
} else {
y /= 2;
x = x*x%mod;
}
}
return t%mod;
}
对于small practice的解法 import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Scanner;
public class RoundBProblemB {
public static void main(String[] args) throws FileNotFoundException {
PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream("outB-small.txt")));
System.setOut(out);
System.setErr(out);
Scanner scanner = new Scanner(new FileInputStream("B-small-practice.in"));
int T = scanner.nextInt();
for (int i = 1; i <= T; i++) {
int A = scanner.nextInt();
int B = scanner.nextInt();
int N = scanner.nextInt();
int K = scanner.nextInt();
System.out.println("Case #" + i +": " + Solve(A,B,N,K));
}
out.flush();
out.close();
}
public static int Solve(long A,long B,long N,long K) {
int ans = 0;
int i = 1,j = 1;
for (i = 1; i <= N; i++) {
long sumA = power(i,A,K);
sumA = sumA%K;
for (j = 1; j <= N; j++) {
if (i == j) {
continue;
} else {
long sumB = power(j,K);
sumB = sumB%K;
if ((sumA + sumB)%K == 0) {
ans++;
}
}
}
}
return ans;
}
/***
*
* @param x
* @param y
* @param mod
* @return
*/
public static long power(long x,long mod) {
long t = 1;
while (y > 0) {
if (y % 2 == 1) {
y -= 1;
t = t*x%mod;
} else {
y /= 2;
x = x*x%mod;
}
}
return t%mod;
}
}
(编辑:晋中站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |

