zoukankan      html  css  js  c++  java
  • 华为上机:统计给定的两个数之间的素数的个数

    统计给定的两个数之间的素数的个数
    描述:

    素数是指在一个大于1的自然数中,除了1和此整数自身外,不能被其他自然数整除的数。

    给定两个数字m和n,统计这两个数字之间素数的个数。

    运行时间限制: 无限制
    内存限制: 无限制
    输入:

    输入为两个整数:m和n

    输出:

    输出m和n之间的素数的个数

    样例输入:
    0 10
    样例输出:
    4
    import java.util.*;
    
    public class Main5{
        public static void main(String[] args){
            Scanner in = new Scanner(System.in);
            while(in.hasNext()){
                String[] strA = in.nextLine().split(" ");
                int a = Integer.parseInt(strA[0]);
                int b = Integer.parseInt(strA[1]);
                if(a>b){ // 需要增加
                    int t = a;
                    a = b;
                    b = t;
                }
                long count = countPrime(a,b);
                System.out.println(count);
            }
            
            in.close();
        }
        public static long countPrime(int a,int b){
            long count = 0;
            for(int n=a;n<=b;n++){
                if(isPrime(n)){
                    count++;
                }
            }
            return count;
        }
        public static boolean isPrime(int n){
            if(n<=1){
                return false;
            }
            if(n==2||n==3){
                return true;
            }
            
            if(n%2==0 ||n%3==0){
                return false;
            }
            for(int i=5;i<Math.sqrt(n)+1;i++){
                if(n%i==0){
                    return false;
                }
            }
            return true;
        }
    }
  • 相关阅读:
    GUI 之 JDialog弹窗
    GUI Swing 之 JFrame窗体
    GUI 键盘监听事件
    GUI 窗口监听事件
    GUI 鼠标监听事件,模拟画图工具
    shell编程
    Ubuntu20.04 Linux初识
    rlwrap的使用
    5个相见恨晚的Linux命令,每一个都非常实用
    Bash初识与常用命令
  • 原文地址:https://www.cnblogs.com/theskulls/p/5707274.html
Copyright © 2011-2022 走看看