23년 4월 17일 [알고리즘 - 수학]

sua·2023년 4월 17일
0

알고리즘 가보자고

목록 보기
1/101

백준 10430번 나머지

문제

링크 : https://www.acmicpc.net/problem/10430

나의 풀이

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();
        int c = sc.nextInt();

        System.out.println((a + b) % c);
        System.out.println(((a % c) + (b % c)) % c);
        System.out.println((a * b) % c);
        System.out.println(((a % c) * (b % c)) % c);
    }
}

입력 받은 a, b, c를 조건에 따라 첫째줄부터 네번째줄까지 식에 대한 답을 출력하게 하면 된다!

결과



백준 2609번 최대공약수와 최소공배수

문제

링크 : https://www.acmicpc.net/problem/2609

나의 풀이

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        int b = sc.nextInt();

        int g = GCD(a, b);
        System.out.println(g);
        System.out.println(a * b / g);
    }

    private static int GCD(int a, int b) {
        if(b == 0) {
            return a;
        } else {
            return GCD(b, a % b);
        }
    }
}

최소공배수가 두 수의 곱에서 최대공약수를 나눈 값이라는 것을 이용하여 최대공약수를 구하는 메소드의 결과값을 변수 g에 저장하고 이를 첫째줄에 출력한다. 또한, 둘째줄에는 두 수의 곱에 g를 나눈 값을 출력하게 하면 된다.

결과


백준 1934번 최소공배수

문제

링크 : https://www.acmicpc.net/problem/1934

나의 풀이

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        
        for(int i = 0; i < t; i++) {
            int a = sc.nextInt();
            int b = sc.nextInt();
            System.out.println(a * b / GCD(a, b));
        }
    }
    
    public static int GCD(int a, int b) {
        if(b == 0) {
            return a;
        } else {
            return GCD(b, a % b);
        }
    }
}

최소공배수가 두 수의 곱에서 최대공약수를 나눈 값이라는 것을 이용하여 풀면 된다.

결과

profile
가보자고

0개의 댓글