Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

22.01.17 - [BOJ] 1629. 곱셈 #194

Closed
suhyunsim opened this issue Jan 17, 2022 · 0 comments
Closed

22.01.17 - [BOJ] 1629. 곱셈 #194

suhyunsim opened this issue Jan 17, 2022 · 0 comments
Assignees
Labels
실버 BOJ - 실버 실패 시도했지만 맞지 못한 문제 재귀

Comments

@suhyunsim
Copy link
Owner

문제

핵심 아이디어

  • 시간초과를 해결하기 위해 두 가지 공식을 적용
  1. 거듭제곱
    1-1. 지수(n)가 짝수일 때: a ^ n == (a ^ (n/2)) ^ 2
    1-2. 지수(n)가 홀수일 때: a ^ n == ((a ^ (n/2)) ^ 2) * a
  2. (A*B)%C == (A%C * B%C)%C

어려운 점, 실수

  • 시간초과를 해결하지 못해서 공식을 검색힘

풀이

package main.java.com.poogle.BOJ.Q1629;

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        long a = sc.nextInt();
        long b = sc.nextInt();
        long c = sc.nextInt();
        System.out.println(calculate(a, b, c) % c);
    }

    private static long calculate(long a, long b, long c) {
        if (b == 0) return 1;
        else if (b == 1) return a;
        long tmp = calculate(a, b / 2, c) % c;
        if (b % 2 == 0) return (tmp * tmp) % c; //짝수일 때
        else return (((tmp * tmp) % c) * a) % c; //홀수일 때
    }
}
@suhyunsim suhyunsim added 실버 BOJ - 실버 재귀 labels Jan 17, 2022
@suhyunsim suhyunsim self-assigned this Jan 17, 2022
@suhyunsim suhyunsim modified the milestones: 1월 2주 차, 1월 3주 차 Jan 17, 2022
@suhyunsim suhyunsim added the 실패 시도했지만 맞지 못한 문제 label Jan 17, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
실버 BOJ - 실버 실패 시도했지만 맞지 못한 문제 재귀
Projects
None yet
Development

No branches or pull requests

1 participant