繁体   English   中英

我怎样才能让这个代码打印一个数字中有多少个素数?

[英]How can I make this code print how many prime digits there are in a number?

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

无论如何 - 我试图让这个代码打印用户输入的数字中有多少个素数。 当我运行它时,它会打印该数字具有(一个数字)素数。 但是每次我运行它时它通常都会打印错误的数字。 我想如果我只是将一些变量切换为另一个变量,那会很好,但我不知道我需要更改哪些变量。 +编辑:我很确定我每次都需要更改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; 
    }
}

你能做一些简单的事情,比如预定义已知的素数(因为很少):

import java.util.*;

class Example {

    static Set<Integer> primeDigits = new HashSet<>(Arrays.asList(2, 3, 5, 7));

    public static void main(String args[] ) throws Exception
    {
        Scanner kb = new Scanner(System.in);

        System.out.print("Please enter a positive number: ");

        int theNum = Integer.parseInt(kb.nextLine());

        int counter = 0;

        while (theNum > 0) {
            if (primeDigits.contains(theNum % 10))
            {
                counter++;
            }

            theNum /= 10;
        }

        System.out.println("The number has " + counter + " prime digits.");
    }
}

用法

% java Example
Please enter a positive number: 2147483647
The number has 4 prime digits.
% 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM