[英]Java - Print 5 prime numbers in a row
我的项目是打印 0 到 100 之间的素数,而且每行显示 5 个素数。
//Print first 100 Prime numbers.
for (i = 1; i <= 100; i++) {
int counter=0;
for(num =i; num>=1; num--) {
if(i % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
//Display the output of 5 numbers per row.
System.out.print(" " + i);
if(i % 5 == 1) {
System.out.print("\n");
}
//Prime number is assigned to the empty string class variable.
displayPrimes = displayPrimes + i + " ";
}
}
素数的输出工作正常,我只是努力让它们分配给每行 5 个值。
当前输出如下所示:
0-100 质数是:
2 3 5 7 11
13 17 19 23 29 31
37 41
43 47 53 59 61
67 71
73 79 83 89 97
这是旨在适应每行 5 个值的代码。
//Display the output of 5 numbers per row.
System.out.print(" " + i);
if(i % 5 == 1) {
System.out.print("\n");
}
您不能再次使用i
,您需要使用一个新变量(我使用了currentPrime
)。 因为i
是你的素数本身,而不是素数的索引。
您还需要在 for 循环中将更改i = 1
添加到int i = 1
否则代码将无法编译。
int currentPrime = 1;
for (int i = 1; i <= 100; i++) {
int counter=0;
for(int num =i; num>=1; num--)
{
if(i % num == 0)
{
counter = counter + 1;
}
}
if (counter == 2)
{
//Display the output of 5 numbers per row.
System.out.print(" " + i);
currentPrime++;
if(currentPrime % 5 == 1)
{
System.out.print("\n");
}
//Prime number is assigned to the empty string class variable.
displayPrimes = displayPrimes + i + " ";
}
}
只需再添加一个 int 变量来计算每一行打印了多少素数。 当它连续打印 5 个数字时,它会转到下一行,然后重置计数器(将变量设置为 0)。 像这样:
int count =0;
for (i = 1; i <= 100; i++) {
int counter=0;
for( num =i; num>=1; num--)
{
if(i % num == 0)
{
counter = counter + 1;
}
}
if (counter == 2)
{
//Display the output of 5 numbers per row.
System.out.print(" " + i);
count++;
if(count == 5) {
System.out.print("\n");
count = 0;
}
//Prime number is assigned to the empty string class variable.
displayPrimes = displayPrimes + i + " ";
}
}
通过检查
if (i % 5 == 1)
您正在检查 i 除以 5 后的余数是否为 1。由于 i 是您的质数,这仅意味着每次您的质数是 1 大于 5 的倍数时,将打印一个新行(因此它给了您一个11、31、41 等之后的新行)。
您需要做的是设置一个单独的计数器变量,以跟踪您在该行上打印了多少个素数。 您可以在每次打印新素数时增加此变量,然后打印新行并在达到 5 后重置素数计数变量。
以下是用户提到的指令的代码实现:707090
public class PrimeNumberInRange {
public static void main(String[] args) {
printPrimeNumbersInRange(2, 1000);
}
// returns true/ false
public static boolean isPrime(int n) {
if (n < 2) {
return false;
}
for (int i = 2; i <= n / 2; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
// returns the list of number between min and max...
public static void printPrimeNumbersInRange(int min, int max) {
if (min < 2 || max < 2) {
System.out.println("Invalid range, should start with at least 2");
} else {
int count = 0;
for (int i = 0; i <= max; i++) {
if (isPrime(i)) {
System.out.print(i+" ");
count++;
if (count % 10 == 0 ) {
System.out.println();
}
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.