[수학] - 최소공배수, 최대공약수 구하기

2023. 9. 22. 22:19·Computer Science/Algorithms

최소 공배수

import java.util.*;
public class Main {
    private static int gcd(int a, int b) { 
        if (a == 0) return b;

        return gcd(b%a, a);
        
    }
    
    private static void lcm(int a, int b) {
        System.out.println(a / b);
    }

    public static void main(String[] args) {
        // 여기에 코드를 작성해주세요.
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        lcm(n*m, gcd(n,m));
    }
}

 

 

최대 공약수

import java.util.*;
public class Main {
    private static int gcd(int a, int b) { // 재귀를 이용한 코드
        if (a == 0) return b;

        return gcd(b%a, a);
        
    }
    private static int gcd_for(int n, int m) { // 반복문을 이용한 코드
        int gcd_num = 0;
        for(int i=1; i<=Math.min(n,m); i++) {
            if (n%i==0 && m%i==0) 
                gcd_num = i;
        }
        return gcd_num;
    }
    public static void main(String[] args) {
        // 여기에 코드를 작성해주세요.
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt(); 
        int m = sc.nextInt();
        // 1. 재귀 코드
        //System.out.println(gcd(n,m));

        // 2. 반복문 코드
        System.out.println(gcd_for(n,m));
    }
}

 

 

 

'Computer Science/Algorithms' 카테고리의 다른 글
  • Monotonic Stack
  • [수학] 소수 구하기
  • [트리] 트리의 리프노드 개수 구하기
  • [트리] 트리의 지름 구하기
kimdozzi
kimdozzi
끝까지 포기하지 않으면, 내가 다 이겨!
  • kimdozzi
    도브로
    kimdozzi
  • 전체
    오늘
    어제
    • 분류 전체보기 (132)
      • Problem Solving (49)
        • Baekjoon (29)
        • Programmers (0)
        • LeetCode (17)
        • 삼성 유형 (2)
      • Computer Science (27)
        • Operating System (2)
        • Algorithms (13)
        • Network (6)
        • DataBase (6)
      • Backend (33)
        • JavaScript (0)
        • TypeScript (6)
        • Java (7)
        • Spring Boot (7)
        • Spring Security (6)
        • JPA (2)
        • Mybatis (1)
        • Junit5 (1)
        • Redis (3)
      • DevOps (14)
        • Git, Github (5)
        • docker (4)
        • AWS (3)
        • nginx (2)
      • etc (6)
        • IntelliJ (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • 티스토리
    • 설정
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    TypeScript
    컨테이너
    오블완
    점 업데이트
    누적합
    imos법
    구간 업데이트
    CORS
    인덱스 시그니처
    세그먼트 트리
    백준
    PrefixSum
    타입스크립트
    파이썬
    오프라인 쿼리
    interface
    docker image
    알고리즘
    AWS
    티스토리챌린지
    segment tree
    인터페이스
    삼성기출
    S3
    Bucket
    docker
    도커
    인덱서블 타입
    구간합
    온라인 쿼리
    python
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
kimdozzi
[수학] - 최소공배수, 최대공약수 구하기
상단으로

티스토리툴바