chi
chi

Reputation: 357

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. 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.

Upvotes: 0

Views: 2525

Answers (2)

Cinnam
Cinnam

Reputation: 1922

  1. You don't modify the while - just write an if around it.
  2. Simply decrement n before you start testing for primes.

    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);                    
}

Upvotes: 1

coraxo
coraxo

Reputation: 11

You can simply check for n == 1 before your while-loop and perform the loop in the else-clause.

As for your second question, you are now beginning your while-loop by checking if the entered number n is a prime. You should start checking with 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);                    

}

Upvotes: 0

Related Questions