반응형
문제
내가 짠코드
public class Solution {
public String listPrimes(int num) {
// TODO:
int[] arr = new int[num-1];
int j = 0;
String result = "";
if(num<=2) return result+=num;
else result = "2";
for(int i=3;i<=num;i++){
for(j=2;j<=i;j++){
if(i%j==0) break;
}
if(i==j) result= result + "-" + i;
}
return result;
}
}
reference
public class Solution {
public String listPrimes(int num) {
String result = "2";
for (int candi = 3; candi <= num; candi += 2) {
boolean isPrime = true;
int sqrt = (int) Math.sqrt(candi);
for (int divider = 3; divider <= sqrt; divider += 2) {
if (candi % divider == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
result = result + "-" + candi;
}
}
return result;
}
}
반응형