【问题标题】:How to print another term at the end after the loop? In java如何在循环结束后打印另一个术语?在java中
【发布时间】:2020-03-17 13:41:15
【问题描述】:
import java.util.Scanner;

public class PrimeNumbers {
    public static boolean prime(int num) {
        boolean flag = true;
        for(int i=2;i<=num/2;i++) {
            if(num%i==0) {
                flag = false;
                break;
            }

        }
        return flag;
    }
    public static void main(String[] args) {
        String separator = "";
        Scanner scan = new Scanner(System.in);
        System.out.println("First num:");
        int low = scan.nextInt();
        System.out.println("Second num:");
        int high = scan.nextInt();
        if(low>high||high<=0||low<0||(high-low) == 1) {
            System.out.println("Invalid input");    
            System.exit(0);
        }
        while(low<high) {
            if(prime(low)==true) {
                System.out.printf(separator+"%d",low);
                separator = ",";
            }
            low++;
        }

    }
}

例子:

first num:1
second num:10
Output: 1,2,3,5,7

我的要求是,我需要检查'second num'输入是否为素数,如果不是素数,则打印下一个素数。

例子:

first num:1
second num:
Output: 1,2,3,5,7,11

【问题讨论】:

  • 第二个示例中的第二个数字应该是多少?
  • 对不起,现在是 10 点。

标签: java primes


【解决方案1】:
int lastNumber = high;
if(!prime(lastNumber)) 
{
  while(!prime(++lastNumber));
  // now you have to prime number after the high or that number itself if it 
  //is the prime
}
// now print all numbers and lastNumber in the last


You did num/2 if the first loop which is good for performance but you can increase 
performance even more you can do int sqrt = sqrt(num) , now cast it to int and use it 
int the loop
so if num is 100 in your case you will be doing 50 checks , but in sqrt case on 10 
checks

【讨论】:

    猜你喜欢
    • 2020-10-08
    • 2017-05-20
    • 2022-11-22
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 2017-10-07
    • 2020-07-22
    • 2022-01-23
    相关资源
    最近更新 更多