java源碼——計算大於一個數的最小素數__原始碼

來源:互聯網
上載者:User

根據輸入數字,計算大於一個數的最小素數。

話不多說,直接貼碼。

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;}}


附運行截圖。



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.