根據輸入數字,計算大於一個數的最小素數。
話不多說,直接貼碼。
package com.fuxuemingzhu.countprime.main;import java.util.Scanner;/** * <p> * Title: Main * </p> * <p> * Description:計算大於某個輸入數的最小素數 * </p> * * @author fuxuemingzhu * * @email fuxuemingzhu@163.com * * @date 2014年10月27日 下午4:01:41 */public class CountPrime {/** * inputNum 輸入的整數 */private static int inputNum = 0;/** * <p> * Title: main * </p> * <p> * Description:程式的主函數,從這裡進入 * </p> * * @param args */public static void main(String[] args) {// 給一句引導輸入的引導語System.out.println("請輸入需要計算的整數:");// 擷取鍵盤輸入getInput();// 輸出結果output();}/** * <p> * Title: getInput * </p> * <p> * Description:擷取鍵盤的輸入結果 * </p> */private static void getInput() {// //利用Scanner 類 擷取鍵盤操作Scanner inputScanner = new Scanner(System.in);inputNum = inputScanner.nextInt();// ///關閉inputScannerinputScanner.close();}/** * <p> * Title: output * </p> * <p> * Description:輸出操作,同時進行了輸入的判斷 * </p> */private static void output() {if (checkInput(inputNum)) {System.out.println("大於這個數的最小素數是:" + countPrime(inputNum));} else {System.out.println("輸入錯誤。需要輸入一個正整數。");}}/** * <p> * Title: checkInput * </p> * <p> * Description:需要輸入一個正整數 * </p> * * @param num * @return 輸入是否正確 */private static boolean checkInput(int num) {if (num >= 1) {return true;}return false;}/** * <p> * Title: countPrime * </p> * <p> * Description:計算大於num的最小素數 * </p> * * @param num * @return 大於num的最小素數 */private static int countPrime(int num) {// ///////////////大於這個數的最小素數int answer = num + 1;// 上面+1是從這個數的下一個數去判斷,而不判斷這個數本身是不是一個素數while (isPrime(answer)) {answer++;}return answer;}/** * <p> * Title: isPrime * </p> * <p> * Description:判斷一個數是不是素數 * </p> * * @param num * @return 一個數是不是素數 */private static boolean isPrime(int num) {boolean check = false;// //////計算到這個數的平方根,減少計算步驟for (int i = 2; i <= Math.sqrt(num); i++) {// /////判斷一個數整除變數i的餘數是否為0,為零說明能整除,則不是素數if (num % ((int) i) == 0) {return true;}}return check;}}
附運行截圖。