본문 바로가기
알고리즘

페르마의 소정리

by 출근길 2018. 7. 17.


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;

public class Main {

	/*
	 * 이항 계수 3
	 * https://www.acmicpc.net/problem/11401
	 */
	public static void main(String[] args) throws IOException {

		//System.setIn(new FileInputStream("res/algo2/E.txt"));
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
		
		StringTokenizer ST = new StringTokenizer(br.readLine());
		
		long N = Long.parseLong(ST.nextToken());
		long K = Long.parseLong(ST.nextToken());
		long MOD = 1000000007;
		long A = N-K;
		
		long n = 1;
		long a = 1;
		long k = 1;
		
		//N!
		for (int i = 1; i <= N; i++){
			n *= i;
			n %= MOD;
		}
		
		//K!
		for (int i = 1; i <= K; i++){
			k *= i;
			k %= MOD;
		}
		
		//(N-K)!
		for (int i = 1; i <= A; i++){
			k *= i;
			k %= MOD;
		}
		
		
        //a^98 = (a^49)^2
		long POW = MOD-2;
		while (POW >= 1){
			if (POW%2 == 1){
				n = (n*k)%MOD;
			}
			k = (k*k)%MOD;
			POW /= 2;
		}
		
		bw.write(n+"\n");
		
		br.close();
		bw.flush();
		bw.close();
	}


'알고리즘' 카테고리의 다른 글

벨만포드  (0) 2018.09.11
최장 증가 수열 (LIS : Longest Increasing Subsequence)  (0) 2018.07.19
에라토스 테네스의 체  (0) 2018.07.18
최소 공통 조상(LCA : Lowest Common Ancestor)  (0) 2018.07.18
Union-Find  (0) 2018.07.17
위상정렬 (Topological Sort)  (0) 2018.07.17
SPFA (Shortest Path Faster Algorithm)  (0) 2018.07.17
인덱스 트리 (Indexed Tree)  (0) 2018.07.17