首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何让此代码打印一个数字中有多少个质数数字?

如何让此代码打印一个数字中有多少个质数数字?
EN

Stack Overflow用户
提问于 2020-01-31 12:45:44
回答 2查看 112关注 0票数 0

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

不管怎样,我试图让这个代码打印出用户输入的数字中有多少个质数位。当我运行它时,它会打印具有(一个数字)质数的数字。但我每次运行它时,它通常都会打印出错误的数字。我认为如果我只是将一些变量换成另一个变量,这将是很好的,但是我不知道我需要改变哪些变量。+edit:我非常确定每次都需要更改theNum的值,但我不确定如何才能做到。我尝试将x++更改为theNum%10,但系统提示必须增加x。顺便说一句,我做theNum%10是因为我需要单独测试theNum的每一个数字。

代码语言:javascript
复制
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;
EN

回答 2

Stack Overflow用户

发布于 2020-01-31 19:33:34

代码语言:javascript
复制
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; 
    }
}
票数 0
EN

Stack Overflow用户

发布于 2020-02-01 08:05:28

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

代码语言:javascript
复制
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.");
    }
}

使用

代码语言:javascript
复制
% java Example
Please enter a positive number: 2147483647
The number has 4 prime digits.
% 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59997989

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档