//cnt만큼 소수 출력(10개 마다 줄바꿈)
//함수를 이용하지 않고 메인에서 for문 2개로도 가능
package java_2022_winter;
public class hw3 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i=2;
int cnt=0;
System.out.println("처음 50개의 소수는:");
while(cnt<50) { //출력할 소수의 개수(cnt가 50이 되면 loop탈출)
boolean check=prime(i);
if(check) {
System.out.printf("%5d",i);
cnt+=1;
if(cnt%10==0) {
System.out.println();
}
}
i+=1;
}
}
public static boolean prime(int i) {
//소수는 1과 자기 자신을 제외한 나머지와 나눠지므로, 2부터 나눈다.
for(int j=2;j<i;j++) {
if(i%j==0) {
return false;
}
}
return true;
}
}
//결과
public static void main(String[] args) {
// TODO Auto-generated method stub
int i=2;
int cnt=0;
System.out.println("처음 50개의 소수는:");
while(cnt<50) { //출력할 소수의 개수(cnt가 50이 되면 loop탈출)
boolean check=prime(i);
if(check) {
System.out.printf("%5d",i);
cnt+=1;
if(cnt%10==0) {
System.out.println();
}
}
i+=1;
}
}
public static boolean prime(int i) {
//소수는 1과 자기 자신을 제외한 나머지와 나눠지므로, 2부터 나눈다.
for(int j=2;j<i;j++) {
if(i%j==0) {
return false;
}
}
return true;
}
}
//결과
댓글
댓글 쓰기