java - 如何让这段代码打印一个数字中有多少个素数?

标签 java logic primes

我遇到的问题和到目前为止我得到的每个回复之间的区别在于,我试图让代码打印有多少个数字是素数,而不是原始数字中有多少个素数。例如,如果用户输入 567,我需要测试 5、6 和 7,并判断有多少是素数。

无论如何 - 我试图让这段代码打印用户输入的数字中有多少个质数数字。当我运行它时,它会打印 The number has (a number) primenumbers。但每次运行时它通常都会打印错误的数字。我想如果我只是将一些变量切换为另一个变量,那就很好了,但我不知道需要更改哪些变量。 +编辑:我很确定我每次都需要更改 theNum 的值,但我不确定如何做到这一点。我尝试将 x++ 更改为 theNum%10 但它说 x 必须增加。顺便说一句,我正在执行 theNum%10 因为我需要单独测试 theNum 的每个数字。

int choice = 3, theNum, copy, x, y, counter, even, odd, zero;

System.out.print("Please enter a positive number ");
theNum = Integer.parseInt(kb.nextLine());

case 3:
    // using nested for loops print the prime numbers 
    counter = 0;
    for (x = 1; x <= theNum; x++) {
        for (x = 2; x <= theNum; x++) {
            if (theNum % 10 % x == 0) counter++;
        }
    }
    System.out.print("The number has " + counter + " prime numbers.");
    break;

最佳答案


class TestClass {
    public static void main(String args[] ) throws Exception {

        Scanner kb = new Scanner(System.in);

        int theNum,counter=0,remainder;      

        System.out.print("Please enter a positive number ");
        theNum = Integer.parseInt(kb.nextLine());  

        while(theNum>0) {
            remainder = theNum%10;

            if(isPrime(remainder))
                counter++;

            theNum = theNum/10;
        }      
        System.out.print("The number has " + counter + " prime numbers.");
    }

    static boolean isPrime(int n) 
    { 
        if (n <= 1) return false; 

        for (int i = 2; i < n; i++) 
            if (n % i == 0) 
                return false; 

        return true; 
    }
}

关于java - 如何让这段代码打印一个数字中有多少个素数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59997989/

相关文章:

c - 如何循环遍历一组(提示)并在继续循环之前一次回答每个提示?

c - 根据用户输入求解表达式

mysql - 在 MySQL 中为 false 或 false = true?非常奇怪的行为

algorithm - 找到小于给定数的 2 个素数的最大乘积

scala - 测试有序无限流是否包含值

Java未初始化变量错误

java - 表关系 多对多没有 sql 中的中间表?

java - 为什么我的 160kb 应用程序背景在运行时变成了 49 MB?

java - 将 JavaFX Pane 动态加载为插件

primes - 为什么埃拉托斯特尼筛的第二个循环是从当前素数的平方开始的?