강의

멘토링

커뮤니티

Inflearn Community Q&A

gkwlsdnjs955037's profile image
gkwlsdnjs955037

asked

Introduction to Java Algorithm Problem Solving: Coding Test Preparation

5. Prime Number (Sieve of Eratosthenes)

Run Time Error 원인을 못찾겠습니다.

Written on

·

218

0

package matter2_5;

import java.util.Scanner;

public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		
		int num = sc.nextInt();
		
		Main main = new Main();
		System.out.println(main.solution(num));
		
	}
	
	public int solution(int num) {
		int answer = 0;
		int arr[] = new int [20];
		for (int i = 2; i < num; i++) {
			if(arr[i] == 0) answer++;
			for (int j = i; j < num; j+=i) {
				arr[j] = 1;
			}
		}
		return answer; 
	}
}

20을 넣었을 때 return 으로 8이 나오는데 Runtime Error 원인을 못찾겠습니다.

java코테 준비 같이 해요!

Answer 1

0

codingcamp님의 프로필 이미지
codingcamp
Instructor

안녕하세요^^

배열의 크기를 20으로 고정하면 안됩니다.

아래와 같이 잡아보세요

int arr[] = new int [num+1];

 

 

gkwlsdnjs955037's profile image
gkwlsdnjs955037

asked

Ask a question