大数取余数-----x的y次方取余数

大数取余数---

题目描述:


输入一个位数不超过10^6的整数a,求a%5并输出


//此题肯定不能用long,int表示要输入的这个整数,这两种类型表示的范围没有题目要求的那么大;可用string

#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, B, 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 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;
	}

}






©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页