帮助java程序(素数) [英] Help with a java program (prime numbers)

查看:76
本文介绍了帮助java程序(素数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会感谢你给我的任务提供帮助。



素数是一个大于1的整数,只能被1和它本身整除。

完成isPrime()方法,它采用整数参数。此方法

返回一个布尔值:如果参数为prime,则为true,否则为false。执行

方法中所需的计算;不要只使用预先计算的

素数列表或if-else链!



这就是我所拥有的。

我不知道应该在哪里放置我的印刷语句,这样当输入一个数字时,它会告诉你它是否是素数。



I''d appreciate help on the task I am given.

A prime number is an integer greater than 1 that is only evenly divisible by 1 and itself.
Complete the isPrime() method, which takes an integer argument. This method
returns a boolean value: true if the argument is prime, and false otherwise. Perform
the required calculations in your method; DO NOT simply use a list of pre-calculated
prime numbers or an if-else chain!

This is what I have.
I don''t know where I should place my print statements so that when a number is entered, it tells you whether or not it is prime.

public static boolean isPrime(int n){
System.out.println("Enter a number to determine if it is prime: ");
boolean prime = true;

if (n % 2 == 0){
return false;
}
for (int i = 3; i < n; i++){
if (n % i == 0){
prime = false;
break;
}
return prime
}

推荐答案

你好



YOur

System.out.println("Enter a number to determine if it is prime: ");





不应该在功能内部。



你需要的功能外部(伪代码)





shouldn''t be inside the function.

OUTSIDE of the function you would need to have (pseudoCode)

Ask the user for a number
Get the number from the user
Call the function, passing the number entered
if (the Function Returned True)
    Tell the user it's a prime
Else
    Tell the user it's not a prime





因此函数本身只能计算数字是否为素数。这样,如果你将来找到一个更好的算法(提示看看PiebaldConsult的提示!),你可以重写那个函数而不会弄乱程序的其余部分。



祝你好运!



So the function itself JUST calculates if the number is a prime. That way, if you find a better algorithm in the future (hint see PiebaldConsult''s hint!), you can just rewrite that one function without messing up the rest of the program.

Good luck!


这篇关于帮助java程序(素数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆