简体   繁体   English

最大数素数小于给定数java

[英]the biggest number prime less than a given number java

My problem is pretty simple but I can't figure out how to resolve how I want to. 我的问题很简单,但是我不知道该如何解决。 I have to find the biggest number prime less than a given number and if there isn't exist to print a message. 我必须找到小于给定数字的最大数素数,如果不存在,则无法打印消息。

import java.util.Scanner;

public class Ex8 {
    public static void main(String[] args){
        int n;
        System.out.println("Give the number: ");
        Scanner in = new Scanner(System.in);
        n=in.nextInt();
        while(prim(n) == false){
            n--;
        }                                     
        System.out.println(n);                    

    }


    public static boolean prim(int m){
        int n=m;
        for(int i=2;i<n;i++){
            if(n%i == 0){
                return false;
            }

        }   
        return true;
    }
}

The code works, if the number is 10 it prints 7 but I want to make 2 new modifications and I can't find the solutions.For example how my program should be modified to print a message if the given number is 1?I've tried to write an if-else but if I modified the while with if, this wouldn't be helpful. 代码有效,如果数字为10,它将打印7,但我想进行2次新修改,但找不到解决方案。例如,如果给定数字为1,我应该如何修改程序以打印消息?我试图写一个if-else,但是如果我用if修改while的话,那将无济于事。 And the second thing, how to make such that if the given number is a prime nr the code still finding the less number than the given one.If I give the number 7 the output is also 7. Thank you. 第二件事,如果给定的数字是质数,那么如何使代码仍然找到比给定的数字少的数字。如果我给数字7,输出也为7。谢谢。

  1. You don't modify the while - just write an if around it. 你不修改while -只写一个if它周围。
  2. Simply decrement n before you start testing for primes. 在开始测试素数之前,只需减小n

     if (n < 2) { System.out.println("Number must be greater than 1"); } else { n--; while (!prim(n)) { n--; } System.out.println(n); } 

Or alternatively: 或者:

if (n < 2) {
    System.out.println("Number must be greater than 1");
} else {
    while (!prim(--n));                                     
    System.out.println(n);                    
}

You can simply check for n == 1 before your while-loop and perform the loop in the else-clause. 您可以在while循环之前简单地检查n == 1,然后在else子句中执行循环。

As for your second question, you are now beginning your while-loop by checking if the entered number n is a prime. 至于第二个问题,您现在通过检查输入的数字n是否为质数来开始while循环。 You should start checking with n-1. 您应该从n-1开始检查。

int n;
System.out.println("Give the number: ");
Scanner in = new Scanner(System.in);
n=in.nextInt();
if (n == 1) {
  System.out.println("Your message here");
} else {
    n -= 1;
    while(prim(n) == false){
        n--;
    }                                         
System.out.println(n);                    

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM