identify prime number using recursive method [java] - java

the problem is below. main() checks numbers 1-10 by calling isPrime(). I think I have the math right however every number other than 2 comes back as not prime.
I have checked some of the solutions and questions on SO, however, I can't seem to achieve the same results.
original problem:
public class PrimeChecker {
// Returns 0 if value is not prime, 1 if value is prime
public static int isPrime(int testVal, int divVal) {
// Base case 1: 0 and 1 are not prime, testVal is not prime
// Base case 2: testVal only divisible by 1, testVal is prime
// Recursive Case
// Check if testVal can be evenly divided by divVal
// Hint: use the % operator
// If not, recursive call to isPrime with testVal and (divVal - 1)
return 0;
}
public static void main(String[] args) {
int primeCheckVal = 0; // Value checked for prime
// Check primes for values 1 to 10
for (primeCheckVal = 1; primeCheckVal <= 10; ++primeCheckVal) {
if (isPrime(primeCheckVal, (primeCheckVal - 1)) == 1) {
System.out.println(primeCheckVal + " is prime.");
}
else {
System.out.println(primeCheckVal + " is not prime.");
}
}
}
}
My solution so far:
public class PrimeChecker {
// Returns 0 if value is not prime, 1 if value is prime
public static int isPrime(int testVal, int divVal) {
int resultVal = 0;
if ((testVal == 0) || (testVal == 1)){
resultVal = 0;
}// Base case 1: 0 and 1 are not prime, testVal is not prime
else if (divVal == 1) {
resultVal = 1;
}// Base case 2: testVal only divisible by 1, testVal is prime
else {
if((testVal % divVal != 0) && (testVal / divVal == 1)) {
isPrime(testVal, (divVal-1));
}
else {
resultVal = 1;
}
}
return resultVal;
}
public static void main(String[] args) {
int primeCheckVal = 0; // Value checked for prime
// Check primes for values 1 to 10
for (primeCheckVal = 1; primeCheckVal <= 10; ++primeCheckVal) {
if (isPrime(primeCheckVal, (primeCheckVal - 1)) == 1) {
System.out.println(primeCheckVal + " is prime.");
}
else {
System.out.println(primeCheckVal + " is not prime.");
}
}
}
}

Change the if/else block
if((testVal % divVal != 0) && (testVal / divVal == 1)) {
isPrime(testVal, (divVal-1));
}
else {
resultVal = 1;
}
to
if (testVal % divVal != 0) {
return isPrime(testVal, (divVal-1));
} else {
resultVal = 0;
}
Basically, you've forgotten to return the result of your recursion, so the code carries on to return the wrong thing. If testVal % divVal == 0, the number is non-prime so you return zero. Also, don't use ints that only take the value of zero or one; use a boolean.

According your question, I think the following code would be easier.
public class PrimeChecker {
// Returns 0 if value is not prime, 1 if value is prime
public static int isPrime(int testVal, int divVal) {
// Base case 1: 0 and 1 are not prime, testVal is not prime
if (testVal <= 1) {
return 0;
}
// Base case 2: testVal only divisible by 1, testVal is prime
if (divVal == 1) {
return 1;
}
// Recursive Case
// Check if testVal can be evenly divided by divVal
// Hint: use the % operator
if (testVal % divVal == 0) {
return 0;
}
// If not, recursive call to isPrime with testVal and (divVal - 1)
return isPrime(testVal, divVal - 1);
}
public static void main(String[] args) {
int primeCheckVal; // Value checked for prime
// Check primes for values 1 to 10
for (primeCheckVal = 1; primeCheckVal <= 10; ++primeCheckVal) {
if (isPrime(primeCheckVal, (primeCheckVal - 1)) == 1) {
System.out.println(primeCheckVal + " is prime.");
}
else {
System.out.println(primeCheckVal + " is not prime.");
}
}
}
}

Related

How do I get an if statement to check if a user given number is a prime number?

I am writing a very basic program in Java to check if a number given by the user is a prime number.
I have tried to use an if statement to check if the number divided by itself is equal to 1 as well as if it is divided by 1 it equals itself, but when I run the program and enter a number there is no reaction at all from the if statement.
package prime.java;
import java.util.Scanner;
public class Prime {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Welcome to Prime!\nPlease enter a number:");
Scanner Scan = new Scanner (System.in);
int number = Scan.nextInt();
System.out.println(number);
if (number%1 == number && number%number == 1) {
System.out.println(number + " is a prime num");
}
}
}
Am I using the right operators?
This can help you:
static bool isPrime(int number)
{
for (int i = 2; i < number; i++)
{
if((number% i) == 0)
{
// Not Prime
return false;
}
}
// Just Prime!
return true;
}
A prime number is not divisible by any numbers between 2 and (itself - 1).
This way, if you call 'isPrime()' inside the if, this just works.
Hope this can help you!
, but when I run the program and enter a number there is no reaction
at all from the if statement.
This is because the if condition is never fulfilled ( for example : n%n will be 0 always) .
Thus, you can keep a variable i that starts from 2 till number -1 and check if that number divided by i , the remainder should never be 0 .
public class PrimeNumber {
public static void main(String[] args) {
int k = 5;
boolean isPrime = true;
for (int i = 2; i < k; i++) {
if (k % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.println("number " + k + " is prime");
} else {
System.out.println("number " + k + " is not prime");
}
}
}
and the output is :
number 5 is prime
You can write a isPrime function to check if a given number is a prime or not, like below
public static boolean isPrime(int n) {
// Corner case
if (n <= 1) {
return false;
}
// Check from 2 to n-1
for (int i = 2; i < n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
And replace your
if (number%1 == number && number%number == 1)
to
if (isPrime(number)
This is more efficient:
boolean isPrime(int number) {
int root = (int) Math.sqrt(number);
for (int i = 2; i <= root; i++) {
if ((number % i) == 0) {
return false;
}
}
return true;
}
Looks like someone is doing a project Euler problem.
You are close but I would suggest maybe looking into how you check if something actually is a prime number as the other comment suggested.
Research also some specifics of prime numbers, I will give one away which is : no prime number ends with 5. Implementing such rules can drastically reduce your programs run time.
And also you want to check out the correct usage of the modulo (%) operator.
public static boolean isPrime(Long num){
String number = String.valueOf(num);
if(number.length() >= 2 ){
//Lets see if a number ends with 5 if it does it is divisible by 2 and not prime
if(number.endsWith("5")){
return false;
}
}
//No reason to check if a number is prime when it is 2.
else if (num == 2){
return true;
}
//Any number that can be devided by 2 with no remainder clearly isn't prime
else if(num % 2 == 0){
return false;
}
//All other numbers actually need to be checked.
else{
for (Long i = num -1; i > 2; i--) {
if(num % i == 0){
return false;
}
}
}
return true;
}

How to factor a number and determine whether its a prime number

So i have this problem where when i factor a number, lets say 15, i have to display this: 15=3x5 but instead what i get is 3x5x5 and i have no clue of how to make it that so it only displays 3x5. And then another problem i have is to find whether the number i inputted is a prime number or not. Any way of fixing this? I just need that and the other stuff im gonna edit after that.
public class PrimeFactor
{
public static void main(String[] args)
{
Scanner input= new Scanner(System.in);
int a;
int d;
int remainder=0;
int count=2;
int c=0;
String s;
System.out.println("Enter an integer to be factored:");
a=input.nextInt();
s="";
d=a;
while(a>1)
{
if(a>1)
{
s="";
while(a>1)
{
remainder=a%count;
if (!(remainder>0))
while(remainder==0)
{
remainder=a%count;
if (remainder==0)
{
a=a/count;
c=c+1;
s=s+count+"x";
if (a==1)
s=s+count;
}
else
count++;
}
else
count++;
}
if (a%count==0)
{
System.out.println(d +"=" + s);
System.out.println(d+" is a prime number.");
}
else
System.out.println(d +"=" + s);
}
// TODO code application logic here
}
}
}
This determines if the number is prime or not the quickest way. Another method would be to use a for loop to determine the number of factors for the number and then say it's prime if it has more than two factors.
int num; // is the number being tested for if it's prime.
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) // only have to test until the square root of the number
{
if (num%i == 0) // if the number is divisible by anything from 2 - the square root of the number
{
isPrime = false; // it is not prime
break; // break out of the loop because it's not prime and no more testing needed
}
}
if (isPrime)
{
System.out.println(num + " is a prime number.");
}
else
{
System.out.println(num + " is a composite number.");
}
You are not constructing the factorization string quite right:
When you find that 3 divides a=15 you set s to 3x and set a to the quotient, so a=5
When you find that 5 divides a=5 you append 5x to s, so now s is 3x5x. Then you set a to the quotient, which is 1. Since the quotient is now 1, you append 5 again, so now you get 3x5x5.
What you'll want to do is append only 5 when a=1, not 5x5. You have to change this:
s=s+count+"x";
if (a==1)
s=s+count;
to this:
if (a==1) {
s=s+count;
} else {
s=s+count+"x";
}
How about trying like this:-
for(int i = input-1; i > 0; i--) {
if((input % i) == 0) {
if(i == 1)
System.out.println("Number is a prime");
else
System.out.println("Number is not a prime");
break;
}
}
These are quite straight-forward methods you can use to factor a number and determine if it is a prime number:
public static int oneFactor(int i) {
for (int j = 2; j < i; j++) {
if (i % j == 0)
return j;
}
return -1;
}
public static Integer[] primeFactors(int i) {
List<Integer> factors = new ArrayList<Integer>();
boolean cont = true;
while (cont) {
int f = oneFactor(i);
if (i > 1 && f != -1) {
i /= f;
factors.add(f);
} else
factors.add(i);
if (f == -1)
cont = false;
}
return factors.toArray(new Integer[factors.size()]);
}
public static boolean isPrime(int i) {
if (i == 2 || i == 3)
return true;
if (i < 2 || i % 2 == 0)
return false;
for (int j = 3, end = (int) Math.sqrt(i); j <= end; j += 2) {
if (i % j == 0) {
return false;
}
}
return true;
}
I am sure one can use faster algorithms, but those would be at the cost of simplicity, and it doesn't seem like you need high speed methods.
They all operate on ints, but its easy to change them to work with longs.
If you have any questions, feel free to ask!
You want to write a loop which loops through numbers 1 to (Inputted Number). And if you found a factor, you print it and divide the input by the factor. (And test if it can be divided again by the same number), else then skip to the next number.
Keep doing this until your input divides down to 1.
This program will break the number down to prime factors:
public class Factor {
public static void main() {
//Declares Variables
int factor = 15;
int i = 2;
System.out.println("Listing Factors:\n");
while (factor>1) {
//Tests if 'i' is a factor of 'factor'
if (factor%i == 0) {
//Prints out and divides factor
System.out.println(i);
factor = factor/i;
} else {
//Skips to next Number
i++;
}
}
}
}
Output:
Listing Factors:
3
5

heavy prime number in java

A prime heavy number is defined to be one that is the sum of more than one pair of prime numbers. Recall that a prime number is a number greater than 1 whose only divisors are 1 and itself.
For example, 16 is prime heavy because 16=3+13 and 5+11 (note that 3, 5, 11, and 13 are all prime). 24 is prime heavy because 24 = 5+19, 7+17 and 11+13. However, 8 is not prime heavy because 8 = 3+5 but no other pair of primes sums to 8.
Write a function named isPrimeHeavy that returns 1 if its argument is prime heavy, otherwise it returns 0.
The function signature is
int isPrimeHeavy (int n)
You may assume that a function named isPrime already exists that returns 1 if its argument is a prime. You can call this function but do not have to write it.
I did this but it cant return a heavy prime..just returns a prime number...
public class Prime {
public static boolean isPrimeHeavy(int n) {
if (n <= 1) {
return false;
}
if (n == 2) {
return true;
}
for (int i = 2; i <= Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static boolean isPrimeHeavy(int n) {
if (n <= 1) {
return false;
}
if (n == 2) {
return true;
}
if (n % 2 == 0) {
return false;
}
for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
public class PrimeTest {
public PrimeTest() {
}
#Test
public void testIsPrime() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Prime prime = new Prime();
TreeMap<Long, String> methodMap = new TreeMap<Long, String>();
for (Method method : Prime.class.getDeclaredMethods()) {
long startTime = System.currentTimeMillis();
int primeCount = 0;
for (int i = 0; i < 1000000; i++) {
if ((Boolean) method.invoke(prime, i)) {
primeCount++;
}
}
long endTime = System.currentTimeMillis();
Assert.assertEquals(method.getName() + " failed ", 78498, primeCount);
methodMap.put(endTime - startTime, method.getName());
}
for (Entry<Long, String> entry : methodMap.entrySet()) {
System.out.println(entry.getValue() + " " + entry.getKey() + " Milli seconds ");
}
}
}
You can use a single loop to try all the possible first values and you can calculate the second, when you find there is more than one pair, return 1, otherwise return 0.
I have given you this much as a hint because its maths really rather than programming. You will find problems like this at Project Euler. IMHO You shouldn't be expected to know how to solve the maths problem unless you are employed for a maths role, but you should be able to write the code if you are a professional developer.
if((argument % 2 == 0 && argument > 12) || argument == 10) {
return 1;
} else {
return 0;
}
public class Prime {
public static boolean isPrimeHeavy(int n) {
if (n % 2 != 0) {
return false;
}
int found = 0;
for (int i = n-3; i >= (n/2); i -= 2) {
if (isPrime(i) && isPrime(n - i)) {
found++;
if (found == 2)
return true;
}
}
return false;
}
}

What's wrong with this code? Prime Numbers

I know this is not the best nor the most efficient way to find prime numbers; However, I can't seem to find the reason why 169 counts as a prime number (for smaller numbers it works OK as far as I'm concerned).
public static int checkPrime(int num, int i)
{
if (i == num)
return 1;
else
{
if (num % i == 0)
return 0;
else
checkPrime(num, i+1);
}
return 1;
}
Main Class:
System.out.println("Type a number");
number = reader.nextInt();
if ((number % 10) % 2 == 0)
result = 0;
else
result = checkPrime(number, 2);
if (result == 1 || number == 2)
System.out.println(number + " is a prime number");
else
System.out.println(number + " is NOT a prime number");
Replacing int by boolean for better expressiveness, and returning the value of the recursive call, your method looks like this:
public static boolean checkPrime(int num, int i)
{
if (i == num)
return true;
else
{
if (num % i == 0)
return false;
else
return checkPrime(num, i+1);
}
}
It still doesn't work for num < 2, it'll run until i overflows. So as your main prime checking function you can write something like:
public static boolean checkPrime(int num)
{
if(num<2)
return false;
else
return checkPrime(num, 2);
}
btw (number % 10) % 2 is equivalent to number % 2.

How can I improve this code for Project Euler 7?

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
My solution:
public class Prime_Number {
public static boolean isPrime(long n) {
if ((n > 2 && n % 2 == 0) || (n > 3 && n % 3 == 0) || (n > 5 && n % 5 == 0) || n == 0 || n == 1) {
return false;
}
return true;
}
public static void main(String[] args) {
int count = 0;
int prime = 0;
while (prime <= 10001) {
if (isPrime(count) == true) {
prime++;
if (prime == 10001) {
System.out.println(count + " is a prime number" + "(" + prime + ")");
}
}
count++;
}
}
}
But it does not give a correct answer. Please help me to upgrade my code. For instance, program defines a 91 as a prime number, but it is not a prime number. How to improve it?
You need to test the number against every prime less than its square root to ensure it is prime.
You're only testing against 2,3 and 5.
Because storing all the primes is not always space-feasable, a common technique is to test for 2, and then test all odd numbers starting at 3. This requires a loop.
consider:
boolean isPrime(long n) {
if (n < 2) return false;
if (n == 2) return true;
if (n % 2 == 0) return false;
if (n < 9) return true;
if (n % 3 == 0) return false;
long max = (long)(Math.sqrt(n + 0.0)) + 1;
for (int i = 5; i <= max; i += 6) {
if (n % i == 0) return false;
if (n % (i + 2) == 0) return false;
}
return true;
}
A number p is prime if it only divides by itself and 1. You are checking only for divison by 2, 3 and 5. This is not enough. Check for every number till p / 2, or better till sqrt(p).
The following solution checks only the odd numbers to be prime, but it counts 2 as prime from the beginning:
public class A {
static int N = 10001;
private static boolean isOddPrime(long x) {
for ( int i = 3 ; i*i <= x ; i+=2 ) {
if ( x % i == 0 ) {
return false;
}
}
return true;
}
public static void main(String[] args) throws Exception {
long start = System.nanoTime();
int x;
int i = 2; // 3 is the 2nd prime number
for ( x = 3 ; ; x+=2 ) {
if ( isOddPrime(x) ) {
if ( i == N )
break;
i++;
}
}
System.out.println(x);
long stop = System.nanoTime();
System.out.println("Time: " + (stop - start) / 1000000 + " ms");
}
}
Output:
104743
Time: 61 ms
I would comment, but I just joined.
You don't have to check every number between 1 and a numbers square root for potential divisors, you just have to check all previous primes (assuming you start at 1 and iterate up), as any other divisor that is not prime will itself be divisible by a prime of a lower value. the higher the number of primes, the more checks against non prime numbers this saves. the example is in C# but that's more to demonstrate the concept.
//store found primes here, for checking subsequent primes
private static List<long> Primes;
private static bool IsPrime(long number)
{
//no number will have a larger divisor withou some smaller divisor
var maxPrime = Math.Sqrt(number);
// takes the list of primes less than the square root and
// checks to see if all of that list is not evenly
// divisible into {number}
var isPrime = Primes
.TakeWhile(prime => !(prime > maxPrime))
.All(prime => number % prime != 0);
if (isPrime)
Primes.Add(number);
return isPrime;
}
private static long GetNthPrime(int n)
{
//reset primes list to prevent persistence
Primes = new List<long> { 2, 3, 5, 7 };
//prime in starting set
if (Primes.Count >= n)
{
return Primes[n - 1];
}
//iterate by 6 to avoid all divisiors of 2 and 3
// (also have to check i + 2 for this to work)
// similar to incrementing by 2 but skips every third increment
// starting with the second, as that is divisible by 3
for (long i = 11; i < long.MaxValue; i += 6)
{
// only check count if is prime
if ((IsPrime(i) && Primes.Count >= n) || (IsPrime(i + 2) && Primes.Count >= n))
{
break;
};
}
//return end of list
return Primes[n - 1];
}

Categories