반응형
자바 (java) 소인수분해 (Factorization)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
import java.util.Scanner;
// Factorization
public class FactorizationTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int num = input.nextInt();
input.close();
int a[] = new int[num];
int t = 0;
while (num != 1) {
if (num >= 2) {
for (int i = 2; i <= num; i++) {
if (num % i == 0) {
a[t] = i;
t++;
num = num/i;
break;
}
}
}
}
if (t == 1) {
System.out.println(num + " is prime number");
} else {
for (int i = 0; i < t-1; i++) {
System.out.print(a[i] + " x ");
}
System.out.println(a[t-1]);
}
}
}
|
cs |
자바 (java) 소인수분해 (Factorization)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | import java.util.InputMismatchException; import java.util.Scanner; // Factorization public class FactorizationTest { public static void main(String[] args) { execute(); } private static void execute() { System.out.println(printResult(getInputNumber())); } private static int getInputNumber() { try (Scanner input = new Scanner(System.in)) { try { System.out.print("Input a number: "); int num = input.nextInt(); if (num <= 1) throw new Exception(); return num; } catch (InputMismatchException ime) { System.out.println("Input type integer!!"); return getInputNumber(); } catch (Exception e) { e.printStackTrace(); try { Thread.sleep(100); // throws InterruptedException } catch (InterruptedException ie) { ie.printStackTrace(); } System.out.println("Input integer bigger than 1!!"); return getInputNumber(); } } } private static String printResult(int num) { int a[] = new int[num]; int orgNum = num; int count = 0; while (num != 1) { for (int i = 2; i <= num; i++) { if (num % i == 0) { a[count] = i; count++; num = num/i; break; } } } StringBuffer sb = new StringBuffer(); if (count != 1) { sb.append(orgNum + " = "); for (int i = 0; i < count-1; i++) { sb.append(a[i] + " x "); } sb.append(a[count-1]); } else { sb.append(orgNum + " is prime number"); } return sb.toString(); } } | cs |
반응형
'JAVA 자바 > JAVA 실습_기초' 카테고리의 다른 글
[JAVA #20] 공통 배수 찾기 (0) | 2020.06.03 |
---|---|
[JAVA #19] 최대공약수_유클리드 호제법 (0) | 2020.05.29 |
[JAVA #17] 배열의 합계 및 평균 (0) | 2020.05.25 |
[JAVA #16] 입력한 숫자 소수 판별 (0) | 2020.05.17 |
[JAVA #15] 100이하 가장 큰 소수 (0) | 2020.05.17 |