-
section3.4알고리즘 2025. 8. 13. 20:46
N입력으로 양의 정수 N이 입력되면 2개 이상의 연속된 자연수의 합으로 정수 N을 표현하는 방법의 가짓수를 출력하는 프로그램을 작성하세요. 만약 N=15이면 7+8=15 4+5+6=15 1+2+3+4+5=15 와 같이 총 3가지의 경우가 존재한다. 입력 첫 번째 줄에 양의 정수 N(7<=N<1000)이 주어집니다. 출력 첫 줄에 총 경우수를 출력합니다. 예시 입력 1 15 예시 출력 1 3ANSWER
public class Question5V2 { public static void main(String[] args) { Question5V2 T = new Question5V2(); Scanner sc = new Scanner(System.in); int n = sc.nextInt(); System.out.println(T.Solution(n)); } public int Solution(int n) { // 1부터 N까지 배열 만들기 // 투포인트로 합 구하기 ? List<Integer> tmpIntArr = new ArrayList<>(); for (int i = 1; i < n; i++) { tmpIntArr.add(i); } for (int a : tmpIntArr) { System.out.print(a + " "); } int cnt = 0; int lt = 0; int sum = 0; // 1 2 3 4 5 6 7 8 9 10 11 12 ... // 1+2+3+4+5=15 for (int rt = 0; rt < n-1; rt++) { sum += tmpIntArr.get(rt); if (sum == n) { cnt ++; } while (sum >= n) { sum -= tmpIntArr.get(lt++); if (sum == n) { cnt ++; } } } return cnt; } }SOLUTION_V1
public class Answer5 { public static void main(String[] args) { Answer5 T = new Answer5(); Scanner s = new Scanner(System.in); int n = s.nextInt(); System.out.println(T.solution(n)); } public int solution(int n) { int answer = 0; int sum = 0; int lt = 0; int m = n/2 + 1; int[] arr = new int[m]; for (int i =0; i < m; i++) { arr[i] = i+1; } for (int rt = 0; rt < m; rt++) { sum += arr[rt]; if (sum == n) { answer ++; } while (sum >= n) { sum -= arr[lt++]; if (sum == n) { answer ++; } } } return answer; } }- 앞 문제와 비슷해서 어렵지 않게 풀었다
- 이 문제를 풀면서 for문 돌릴 때 절반만 돌려도 되었었는데 신경 쓰지 못했다
- ArrayList를 자주 쓰다보니 list로 만들어서 풀었는데 순간 리스트/배열 차이가 뭐지?라는 생각이 들었고 금방 떠오르지 않았다
- 배열은 정적으로 크기가 고정되어 있고 리스트는 동적이다
- 따라서 배열은 스택영역에 저장되며 리스트는 힙영역에 저장된다
- 배열 > 리스트 변환 : Arrays.asList
SOLUTION_V2
public class Answer5V2 { public static void main(String[] args) { Answer5V2 T = new Answer5V2(); Scanner s = new Scanner(System.in); int n = s.nextInt(); System.out.println(T.solution(n)); } public int solution(int n) { int answer = 0; int cnt = 1; n--; while (n > 0) { cnt ++; n = n - cnt; if (n % cnt == 0) { answer++; } } return answer; } }수학적으로 푸는 다른 방법인데 신기하다
728x90'알고리즘' 카테고리의 다른 글
section5.1 (3) 2025.08.14 section3.5 (1) 2025.08.13 section3.3 (0) 2025.08.13 section3.2 (0) 2025.08.09 section3.1 (2) 2025.08.09