In this shot, we will discuss how to check whether a given number is prime or not in Java. Before that, let’s go over what a prime number is. All numbers that are greater than one and have only two factors, i.e., one and the number itself, are identified as prime numbers. We can also understand a prime number as a number that has exactly two divisors. For example, let’s take the numbers two through seven:
Two, three, five, and seven are the numbers that have exactly two divisors, i.e., one and the respective number itself, so they are prime numbers. Four and six are non-prime numbers/composite numbers. The isPrime() functionWe can use the isPrime() function, which takes the number as input and returns true if the number is prime and false if it is not. How to find a prime number in Java
CodeLet’s look at an example that takes a number as input and returns a string that states whether the number is a prime number or a non-prime number. Enter a number and then press the ‘RUN’ button. import java.util.Scanner; class Prime { public static void main(String[] args) { Scanner sc= new Scanner(System.in); System.out.println("Enter a number to check if it is truly prime number or not: "); int number= sc.nextInt(); if(isPrime(number)) { System.out.println(number + " is prime number"); } else{ System.out.println(number + " is a non-prime number"); } } static boolean isPrime(int num) { if(num<=1) { return false; } for(int i=2;i<=num/2;i++) { if((num%i)==0) return false; } return true; } }
This way, we can check whether the given number is prime or not in Java. RELATED TAGS This forum is now read-only. Please use our new forums! A better way to this exercise is that when the digit you would submit is a negative int, the function should return something like “A prime can only be a positive number”, instead of False. Anyhow… here is my solution: def is_prime(x): # only positive numbers are allowed and the smallest prime number is 2 if (x > 1): # since the smallest prime number is 2, we start the divisor at 3 divisor = 2 # because the submit number can always be divided by itself we can use the # range function to set the correct range for i in range(divisor,x): if (x % i) == 0: return False else: return False return True print is_prime(3)Just a small variation: def is_prime(x): if x < 2: return False else: for n in range(2,x): if x % n == 0: return False return TrueNow it’s completely correct. I fixed one small thing, and code works properly. The thing is divisor: it should be 2, not 3. Let’s look at code below. Copy it into codeacademy interpreter and run. def is_prime(x): # only positive numbers are allowed and the smallest prime number is 2 if (x > 1): divisor = 2 # because the submit number can always be divided by itself we can use the # range function to set the correct range for i in range(divisor,x): if (x % i) == 0: return False else: return False return True def print_prime(x): if is_prime(x): print str(x) + " is prime." else: print str(x) + " is NOT prime." # ---===TEST===--- print " ---===TEST===---" print print "Test for small numbers:" print for i in range(1, 21): print_prime(i) print print "Test for larger numbers:" print for i in range(100, 121): print_prime(i) print print "Test for other numbers which are only primes:" print print_prime(7877) print_prime(18521) print_prime(70639) print_prime(262121) #Don't worry when your computer must take a few second to make process... Look at that: he must divide every number since 2 till 15481793 - 1... #I would be doing it my whole life and I would die before I would done. print_prime(15481793)As you see everything works great. Numbers, which should be prime - are prime and vice versa. Look more carefully at 1 and 4. Now program says that both are not prime - as should be. It is not completely good. Your code says that 1 is prime… and 4 is prime. Some people would argue that 1 is prime, but 4 definitly is not . You must fix your code. Here is my working code.. Would this be considered pythonic? I didn’t like how 2 needed to be hardcoded, but wasn’t sure of a way around it using my count method. def is_prime(x): #There are no primes below 2 so we immediately discount those if x < 2: return False #Hardcoded 2 as a prime since my count method wouldn't work on 2 elif x == 2: return True else: store = [] for i in range(1, x + 1): store.append(x % i) if store.count(0) > 2: return False elif store.count(0) == 2: return TrueThis fulfills all the conditions that were listed. from math import sqrt def is_prime(x): if x < 2: return False elif x == 2: return True elif x % 2 == 0 or x % sqrt(x) == 0: return False else: return TrueHere’s my slightly altered version from the one posted by Taoh: def is_prime(x): if x < 2: return False else: for n in range(2, x-1): if x % n == 0: return False return TrueThe difference being that we’re more closely following the instructions by checking from range(2,x-1) and not range(2,x) The reason we’re checking with divisors from 2 to x-1 and not just x is because according to the information given:
Therefore, there is no reason to check divisors like 0, 1, and the number itself Also worthy of mention is the fact that Taoh’s method returns a “True” value from outside the for loop: else: for n in range(2, x-1): if x % n == 0: return False return TrueWhile not immediately obvious, this implementation takes care of the pesky problem of when x=2. When x=2, the range of divisors we’re checking has no values at all! Had we attempted to return a “True” value from within the for loop itself, our function would have failed on x=2. Have at thee fellow-coders: def is_prime(n): if n<2: return False elif n==2: return True for i in range(2,int(n/2)+2): # print i if n%i==0: return False return TrueHere is the way I did it. Not the most simple method but it still gets the job done. def is_prime(x): if x>1: if x==2: return True elif x%2==1: count=2 while count < x: if x%count==0: return False else: count+=1 return True else: return False else: return FalseI believe this is somewhat the same approach, only that it stops testing if it is a prime. Please tell me if this isnt a working solution. def is_prime(x): if x < 2: return False else: c = x-1 while c>1: if x%c == 0: return False break c -= 1 else: return Truedef is_prime(x): from math import sqrt if x < 2: return False elif x == 2: return True else: n = 2 while n < x: if x % n == 0 and x != n or x % sqrt(x) == 0 and x != n: return False else: n += 1 else: return True def is_prime(x) : if x < 2: return False elif x == 2 : return True else : for n in range(2,x-1) : if x % n ==0 : return False return True n=raw_input("till what number to find primes ") for x in range (0,int(n)) : if is_prime(x) : print str(x) + "," , |