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 }
  • 相关阅读:
    Linux套接子(c语言)模拟http请求、应答
    709. 转换成小写字母
    1108. IP 地址无效化
    C++大作业——教职工管理系统
    贪吃蛇游戏 1.0
    getch()函数的使用方法及其返回值问题
    Open source project code
    slack Interface operation
    slack init: Simple interaction with slack bot
    mac 使用 Docker 搭建 ubuntu 环境
  • 原文地址:https://www.cnblogs.com/zpoor/p/7522806.html
Copyright © 2011-2022 走看看