Using own method in Java to test a number is prime or not | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Using own method in Java to test a number is prime or not

Hi! I wrote a program to check a number is prime or not using a boolean method. Here is my code: package prim; import java.util.Scanner; public class Prim { public static boolean isPrime(int num) { if ( num % 2 == 0 && num > 2 && num % 1 == 0) { return false; } return true; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Kérem a számot, amiről el kell döntenem, hogy prím-e: "); int n = sc.nextInt(); while (n < 2) { System.out.print("Kérem a számot, amiről el kell döntenem, hogy prím-e: "); n = sc.nextInt(); } boolean m = isPrime(n); if (isPrime(n)) { System.out.println("A szám prím."); } else { System.out.println("A szám nem prím."); } } } The problem is, it says to 45 and 93 are prime numbers, but they aren't. Where's the problem in the code? Thanks in advance.

3rd Mar 2019, 5:01 PM
Tibor Tóth
Tibor Tóth - avatar
3 Answers
+ 2
A prime number is divisible by 1 and itself only. You can check if a number is prime by confirming if it is divisible by any other number asides 1 and itself. For that you can use a for loop. Something like for(int num = 2; i < theNumberwetesting; i++){ //check if its divisible by i } loop started from 2 to avoid zero division error and because it is surely going to be divisible by 1. For a faster performance you can set the loop limit to numberWeAreTesting/2
3rd Mar 2019, 5:24 PM
Ore
Ore - avatar
+ 2
Nice one @Tibor Toth 🤔Sometimes i really wish i could upvote things https://www.sololearn.com/Discuss/1089145/?ref=app
3rd Mar 2019, 5:43 PM
Ore
Ore - avatar
+ 1
I solved with while loop: public static boolean isPrime(int num) { int i=2; while(i<= num/2) { if(num % i == 0) { return false; } i++; } return true; }
3rd Mar 2019, 5:39 PM
Tibor Tóth
Tibor Tóth - avatar