잡다한 코딩/Project Euler (Java)
(Java) Project Euler 005 - Smallest Multiple
Skyleester_devNurse
2023. 12. 14. 18:00
// 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder
// What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
Question)
-- 1부터 10까지 모든 자연수로 나누어 떨어지는 양의 정수 중에 가장 작은 수는 2520이다.
-- 1부터 20까지 모든 자연수로 나누어 떨어지는 양의 정수 중 가장 작은 수를 구하라.
public class ProjectEuler_005 {
public static void main(String[] args) {
int result = Integer.MIN_VALUE; // 1)
for (int i = 2520; i < Integer.MAX_VALUE; i++) { // 2)
if(isEvenlyDivisible(i)){
result = i;
System.out.println("The smallest multiple that is evenly divisible by 1 to 20 is " + result);
break; // 3)
}
}
}
public static boolean isEvenlyDivisible(int num){
for(int i = 2; i <= 20; i++){ // 4)
if(num % i != 0){
return false;
}
}
return true;
}
}
1) 출력될 result 값을 Integer의 최소값으로 초기화.
2) for 루프는 2520부터 시작하여 Integer의 최대값까지로 설정.
3) 값을 찾으면 break로 루프를 종료시켜주기.
4) 2부터 20까지 나누어서 떨어지면 true를 반환.
특별히 어려울 것 없는 문제.