zoukankan      html  css  js  c++  java
  • Java-判断一个数是不是素数

     1 import java.util.Scanner;
     2 
     3 /**
     4  * @author 薛定谔的猫
     5  * java判断一个数是不是素数
     6  * 
     7  * 素数又称质数,是指在一个大于1的自然数中,除了1和本身之外,不能被其他自然数整除的数*/
     8 public class PrimeNumber {
     9     public static void main(String[] args) {
    10         Scanner sc = new Scanner(System.in);//扫描器,接收控制台输入信息
    11         System.out.println("请输入一个大于1的整数:");
    12         
    13         try {
    14             int num = sc.nextInt();//接收控制台输入的整数
    15             
    16             if (isPrime(num)) {//调用isPrime()方法
    17                 System.out.println(num + "是素数");//若isPrime()方法返回true,输出是素数
    18                 
    19             } else {
    20                 
    21                 System.out.println(num + "不是素数");//若isPrime()方法返回false,输出不是素数
    22             }
    23             
    24         } catch (Exception e) {
    25             
    26             System.out.println("请输入整数");//捕获异常,若输入非法数,输出异常
    27         }
    28         sc.close();
    29     }
    30     
    31     /**
    32      * 用于判断一个数是否是素数,如果是,返回true,否则返回false
    33      * @param a 输入的值
    34      * @return true  false*/
    35     
    36     public static boolean isPrime(int a) {
    37         boolean flag = true;
    38         
    39         if (a<2) {//素数不小于2
    40             return false;
    41         } else {
    42             for(int i = 2;i<=Math.sqrt(a);i++) {
    43                 if (a % i == 0) {//若果能被整除则说明不是素数,返回false
    44                     flag = false;
    45                     break;
    46                 }
    47             }
    48         }
    49         return flag;
    50     }
    51 }
  • 相关阅读:
    CodeForces 734F Anton and School
    CodeForces 733F Drivers Dissatisfaction
    CodeForces 733C Epidemic in Monstropolis
    ZOJ 3498 Javabeans
    ZOJ 3497 Mistwald
    ZOJ 3495 Lego Bricks
    CodeForces 732F Tourist Reform
    CodeForces 732E Sockets
    CodeForces 731E Funny Game
    CodeForces 731D 80-th Level Archeology
  • 原文地址:https://www.cnblogs.com/zpoor/p/7522806.html
Copyright © 2011-2022 走看看