2017-02-21-质数拆分
实例1:
控制台输出实现计算器的功能
实例2:
控制台输出实现偶数的质数拆分过程
实例1的核心思想:
输入输出,死循环,提示用户输入结束标志,判断结束标志
实例2的核心思想:
质数判断:1,判断是质素,2,判断不是质数
注意:质数的1,2,很特别,1是唯一的因数为一个的质数,2为质数中唯一的偶数。
实例1核心代码:
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
| while (true) { Scanner scanner = new Scanner(System.in); System.out.println("请输入第一个数字:"); int first = scanner.nextInt(); System.out.println("请输入运算符:"); String str = scanner.next(); System.out.println("请输入第二个数字:"); int second = scanner.nextInt(); System.out.print("计算结果是:");
switch (str) { case "+": System.out.println(first + "+" + second + "=" + (first + second)); break; case "-": System.out.println(first + "-" + second + "=" + (first - second)); break; case "*": System.out.println(first + "*" + second + "=" + (first * second)); break; case "/": System.out.println(first + "/" + second + "=" + (first / second)); break;
default: System.out.println("无法处理"); break; }
|
实例2核心代码:
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
| public class PrimeNumber_beta {
public static void main(String[] args) { PrimeNumber_beta p = new PrimeNumber_beta(); Scanner scanner = new Scanner(System.in); while (true) { System.out.println("请输入一个偶数:"); int input = scanner.nextInt(); if (input % 2 != 0) { System.out.println("此数不是偶数"); } else { for (int i = 1; i < input / 2; i++) { if (p.judege(i) && p.judege(input - i)) { System.out.println(input + "=" + i + "+" + (input - i)); } } } System.out.println("退出请输入quit,输入任意其它的则继续"); String str = scanner.next(); if (str.equals("quit")) { break; } }
}
public boolean judege(int n) { boolean flag = true;
for (int i = 3; i < n; i += 2) { if (n % i == 0) { flag = false; } } return flag; } }
|