๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[JAVA] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ์†Œ์ˆ˜ ์—๋ผํ† ์Šคํ…Œ๋„ค์Šค์˜ ์ฒด

by yunamom 2022. 2. 23.
๋ฐ˜์‘ํ˜•

class Solution {
      public int solution(int n) {
          int answer = 0;
          
          int[] number = new int[n+1];
          
          //2๋ถ€ํ„ฐ n๊นŒ์ง€์˜ ์ˆ˜๋ฅผ ๋ฐฐ์—ด์— ๋„ฃ๋Š”๋‹ค.
          for(int i=2; i<=n; i++) {
              number[i] = i;
          }     
          //2๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด์„œ ๋ฐฐ์ˆ˜๋“ค์„ 0์œผ๋กœ ๋งŒ๋“ ๋‹ค.
          //ํ›„์— 0์ด๋ฉด ๋„˜์–ด๊ฐ€๊ณ  ์•„๋‹ˆ๋ฉด ๊ทธ์˜ ๋ฐฐ์ˆ˜๋“ค์„ ๋‹ค์‹œ 0์œผ๋กœ ๋งŒ๋“ ๋‹ค.
          for(int i=2; i<=n; i++) {
              if(number[i]==0) continue;
              
              for(int j= 2*i; j<=n; j += i) {
                  number[j] = 0;
              }
          }
          
          for(int i=0; i<number.length; i++) {
              if(number[i]!=0) {
                  answer++;
              }
          }     
          return answer;
      }
    }
300x250

์ฝ”๋“œ