-
[JS] 나머지가 1이 되는 수 찾기이노베이션 캠프/3주차_알고리즘 2023. 6. 21. 11:52
문제
https://school.programmers.co.kr/learn/courses/30/lessons/87389
문제 풀이
풀이1. 가장 큰 수부터 확인
function solution(n) { let x = n; // 1) 나눈 나머지가 1이 되도록 하는 가장 작은 자연수 값 저정할 변수 선언 및 할당 // 2) for문 이용하여 주어진 n부터 -1씩 뺀 값에 접근 for (let i=n; i > 0; i--) { if (n % i !== 1) continue; // 2-1) 나머지 값이 1이 아니면 다음으로 넘어감 if (x > i) x = i; // 2-2) 나머지 값이 이전 값이 저장된 x보다 작으면 x의 값 변경 } return x; }
풀이2. 가장 작은 수부터 확인
function solution(n) { let x = n; // 1) 나눈 나머지가 1이 되도록 하는 가장 작은 자연수 값 저정할 변수 선언 및 할당 // 2) for문 사용하여 1부터 n까지 1씩 증가시키면서 확인 for (let i=1; i<n; i++) { if (n % i === 1) { // 2-1) 나머지 값이 1이면 종료 return i; } } return x; }
728x90'이노베이션 캠프 > 3주차_알고리즘' 카테고리의 다른 글
[JS] 폰켓몬 (0) 2023.06.21 [JS] 소수 찾기 (0) 2023.06.21 [JS] K번째수 (0) 2023.06.21 [JS] 최대공약수와 최소공배수 (0) 2023.06.21 [JS] 예산 (0) 2023.06.21