gpt4 book ai didi

Java程序给出两个区间之间的素数

转载 作者:行者123 更新时间:2023-12-02 09:25:58 24 4
gpt4 key购买 nike

我需要一个程序来打印任意两个间隔之间的所有素数,然后打印两个间隔之间有多少个素数。

所以我有一个正在运行的代码,但它不会打印数字 2,而且我知道 2 是素数。它正在正确地执行其他所有操作。我尝试了一些其他可以打印 2 的代码,但如果我输入负数,它也会给出负数。

import java.util.Scanner;

class Main {

public static void main(String args[]) {

int first, last, flag = 0, i, j;

Scanner scanner = new Scanner(System.in);

System.out.print("\nEnter the lower bound : ");
first = scanner.nextInt();
System.out.print("\nEnter the upper bound : ");
last = scanner.nextInt();
System.out.println("The prime numbers in between the entered limits are :");

int x = 0;
for (i = first; i <= last; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
flag = 0;
break;
} else {
flag = 1;
}
}
if (flag == 1) {
x++;
System.out.println(i + " ");
}
}
System.out.println("Total number of prime numbers between " + first + " and " + last + " are " + x);
}
}

所以如果我输入 -5(上限)和 10(下限)它应该打印:2357-5 到 10 之间的质数总数为 4

但是它打印357-5 到 10 之间的质数总数为 3

最佳答案

只需在 for 循环之前添加以下几行,它就会给出预期的输出:

int x = 0;
if (first<3) {
System.out.println(2);
x++;
}

您的更新程序将是:

import java.util.Scanner;

class Main {

public static void main(String args[]) {

int first, last, flag = 0, i, j;

Scanner scanner = new Scanner(System.in);

System.out.print("\nEnter the lower bound : ");
first = scanner.nextInt();
System.out.print("\nEnter the upper bound : ");
last = scanner.nextInt();
System.out.println("The prime numbers in between the entered limits are :");

int x = 0;
if (first<3) {
System.out.println(2);
x++;
}
for (i = first; i <= last; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
flag = 0;
break;
} else {
flag = 1;
}
}
if (flag == 1) {
x++;
System.out.println(i + " ");
}
}
System.out.println("Total number of prime numbers between " + first + " and " + last + " are " + x);
}
}

关于Java程序给出两个区间之间的素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58344658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com