Finding prime numbers with a custom IsPrime method - java

I started learning Java about one month ago and today I saw this question I couldn't solve.
The question was:
Write a method named isPrime, which takes an integer as an argument and returns true
if the argument is a prime number, or false otherwise. Demonstrate the method in a complete program.
And the second part says:
Use the isPrime method that you wrote in previous program in a program that
stores a list of all the prime numbers from 1 through 100 in a file.
Here's my code, which doesn't work:
import java.io.*;
public class PrimeNumbers {
public static void main (String args[]) throws IOException {
PrintWriter outputFile = new PrintWriter("PrimeNumber.txt");
int j = 0;
for (int i = 0; i < 100; i++) {
isPrime(i);
outputFile.println("Prime nums are:" + i);
}
}
public static boolean isPrime (int j) {
int i;
for (j = 2; j < i; j++) {
if (i % j == 0) {
return false;
}
if (i == j) {
return true;
}
}
}
}

Your condition for returning true in isPrime - if (i == j) - can never be met, since it's inside a loop whose condition is j < i. Instead, just return true after the loop. If the loop ends without returning false, you know for sure that the input number is prime.
Your code that uses isPrime is not checking the value returned by this method. You must check it in order to decide whether to write the number to the output file.

import java.io.IOException;
import java.io.PrintWriter;
public class PrimeNumbers
{
public static void main(String args[]) throws IOException
{
PrintWriter primeNumbersWriter = new PrintWriter("PrimeNumber.txt");
for (int i = 0; i < 100; i++)
{
// You didn't do anything with the return value of isPrime()
if (isPrime(i))
{
primeNumbersWriter.println("Prime numbers are: " + i);
}
}
// Please close writers after using them
primeNumbersWriter.close();
}
public static boolean isPrime(int prime)
{
// Do not use the number to check for prime as loop variable, also it's
// sufficient to iterate till the square root of the number to check
for (int number = 2; number < Math.sqrt(prime); number++)
{
if (prime % number == 0)
{
return false;
}
}
// You didn't always return a value, it won't let you compile otherwise
return true;
}
}

Prime Number A prime number (or a prime) is a natural number greater
than 1 that has no positive divisors other than 1 and itself.
What should be the logic?
Pass a number to method.
Use loop to start a check of modulo % to find at least one number which can divide the passed number.
Check until we reached the value passedNumber.
If the modulo gives 0 for atleast one, it's not prime thank god!
If modulo is not 0 for any number ...oh man it's Prime.
What are the problems in your code?
You are looping correctly but using the variable j which is the limit and you are incrementing it!
If you want to loop through i < j how can the condition i == j be true?
If method is returning boolean why are you using method as void! Use that returned value.
You can just return false at the end if divisor not found!
We did it...Just try now!

about isPrime: First of all, u should loop for( j = 2; j*j <= i; j++)
the reason for this loop is that if a number isn't prime, its factor must be less or equal to the squared root of i, so there is no need to loop after that point
now, if loop didn't return false - return true`
about second function: use if before checking isPrime - if(isPrime(i)) {add i to list}

see here is your solution.
import java.util.Scanner;
public class Testing {
public static void main(String args[]) {
Scanner scnr = new Scanner(System.in);
int number = Integer.MAX_VALUE;
System.out.println("Enter number to check if prime or not ");
while (number != 0) {
number = scnr.nextInt();
System.out.printf("Does %d is prime? %s %s %s %n", number,
isPrime(number), isPrimeOrNot(number), isPrimeNumber(number));
}
}
/*
* Java method to check if an integer number is prime or not.
* #return true if number is prime, else false
*/
public static boolean isPrime(int number) {
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 2; i < sqrt; i++) {
if (number % i == 0) {
// number is perfectly divisible - no prime
return false;
}
}
return true;
}
/*
* Second version of isPrimeNumber method, with improvement like not
* checking for division by even number, if its not divisible by 2.
*/
public static boolean isPrimeNumber(int number) {
if (number == 2 || number == 3) {
return true;
}
if (number % 2 == 0) {
return false;
}
int sqrt = (int) Math.sqrt(number) + 1;
for (int i = 3; i < sqrt; i += 2) {
if (number % i == 0) {
return false;
}
}
return true;
}
/*
* Third way to check if a number is prime or not.
*/
public static String isPrimeOrNot(int num) {
if (num < 0) {
return "not valid";
}
if (num == 0 || num == 1) {
return "not prime";
}
if (num == 2 || num == 3) {
return "prime number";
}
if ((num * num - 1) % 24 == 0) {
return "prime";
} else {
return "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;
}

Displaying Palindromic Prime number

I am trying to make a program to display the first 50 prime palindromes with 10 numbers per line. This is the code i have so far, however when run nothing happens. I have looked t similar solutions and can't seem to find were the error is. Any help would be appreciated.
import java.lang.Math;
public class PalindromicPrime {
public static void main(String[] args) {
int counter = 1;
int start = 2;
isPalindrome(start);
isPrime(start);
while (counter <= 50) {
if (isPrime(start) && isPalindrome(start)) {
System.out.print(start + " ");
if (counter % 10 == 0) {
System.out.println();
counter++;
}
start++;
}
}
}
public static boolean isPalindrome(int x) {
int reverse = 0;
while(x > 0) {
reverse = reverse * 10 + x % 10;
x = x / 10;
}
if (reverse == x) {
return true;
}
else {
return false;
}
}
public static boolean isPrime(int x) {
if (x % 2 == 0 && x != 2) {
return false;
}
int sqr = (int)Math.sqrt(x);
for (int i = 3; i <= sqr; i += 2) {
if(x % i == 0) {
return false;
}
}
return true;
}
}
You're not incrementing start when it isn't prime, so you hit an infinite loop when you hit your first non-prime number. Put your start++ outside of the if statement.
Your isPalindrome() method is broken. The variable x is whittled down to create reverse, but then you compare reverse to the modified version of x instead of its original value.
You're only incrementing counter every 10th prime, so this will end up printing 500 palindromic primes, not 50.
Bonus: Finding primes is faster if you store every prime that you find, and then only check division by previously-found primes.
First of all as others have said your isPalindrome() Method is not working correctly.
I would suggest you just convert your int to a string and then check whether that is a Palindrome. I think it is the easiest way. Maybe others can comment whether that is a bad idea in terms of performance.
Here is how I would do it:
public static boolean isPalin(int x) {
String s = Integer.toString(x);
for(int i = 0; i < s.length()/2; i++) {
if(s.charAt(i) != s.charAt(s.length()-i-1)) {
return false;
}
}
return true;
}
Also your while loop is not working correctly as you only increment start when you actually found a prime. Counter should be incremented everytime you found a prime.
On top of that you should base the condition for the while loop on your start value and not the counter for the line breaks.
Edit: Actually you should use counter in the while condition. I was wrong.
Here is the updated code:
public static void main(String[] args) {
int counter = 0;
int start = 2;
while (counter < 50) {
if (isPrime(start) && isPalin(start)) {
System.out.print(start + " ");
counter++;
if (counter % 10 == 0) {
System.out.println();
}
}
start++;
}
}
public static boolean isPalin(int x) {
String s = Integer.toString(x);
for(int i = 0; i < s.length()/2; i++) {
if(s.charAt(i) != s.charAt(s.length()-i-1)) {
return false;
}
}
return true;
}
public static boolean isPrime(int x) {
if (x % 2 == 0 && x != 2) {
return false;
}
int sqr = (int)Math.sqrt(x);
for (int i = 3; i <= sqr; i += 2) {
if(x % i == 0) {
return false;
}
}
return true;
}
Here is the output for the first 50 primes that are palindromic:
2 3 5 7 11 101 131 151 181 191
313 353 373 383 727 757 787 797 919 929
10301 10501 10601 11311 11411 12421 12721 12821 13331 13831
13931 14341 14741 15451 15551 16061 16361 16561 16661 17471
17971 18181 18481 19391 19891 19991 30103 30203 30403 30703
Your code is an Infinite looping. This is because you increment start in the if statement, so only when start is a prime and palindrome number.
If start isn't palindrome or prime, it will not enter the conditional and thus counter will Nevers incréée and reach 50

Java program on "friendly numbers "

I am working on a assignment about so called "friendly-numbers" with the following definition: An integer is said to be friendly if the leftmost digit is divisible by 1, the leftmost two digits are divisible by 2, and the leftmost three digits are divisible by 3, and so on. The n-digit itself is divisible by n.
Also it was given we need to call a method (as I did or at least tried to do in the code below). It should print whether a number is friendly or not. However, my program prints "The integer is not friendly." in both cases. From what I have tried, I know the counter does work. I just cannot find what I am missing or doing wrong. Help would be appreciated, and preferably with an adaptation of the code below, since that is what I came up with myself.
import java.util.Scanner;
public class A5E4 {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Please enter an integer: ");
int friendlyNumber = in.nextInt();
boolean result = isFriendly(friendlyNumber);
if (result)
{
System.out.println("The integer is friendly");
}
else
{
System.out.println("The integer is not friendly");
}
}
public static boolean isFriendly(int number)
{
int counter = 1;
while (number / 10 >= 1)
{
counter ++;
number = number / 10;
}
boolean check = true;
for (int i = 1; i <= counter; i++)
{
if (number / Math.pow(10, (counter - i)) % i == 0 && check)
{
check = true;
}
else
{
check = false;
}
}
return check;
}
}
while (number / 10 >= 1){
counter ++;
number = number / 10;
}
In this bit, you are reducing number to something smaller than 10. That is probably not what you want. You should make a copy of number here.
Also, proper software design would recommend that you extract this to a dedicated method.
private int countDigits(int number){
if(number < 1) throw new IllegalArgumentException();
int n = number;
int counter = 1;
while (n / 10 >= 1){
counter ++;
n = n / 10;
}
return counter;
}
You need to copy the number which you use to find out how much digits your number has. Otherwise you change the number itself and don't know anymore what it was.
The second mistake is that you divide an integer by Math.pow() which returns a double. So your result is double. You want to have an integer to use the modulo operator.
public static boolean isFriendly(int number)
{
int counter = 1;
int tmpNumber = number;
while (tmpNumber / 10 >= 1)
{
counter ++;
tmpNumber = tmpNumber / 10;
}
boolean check = true;
for (int i = 1; i <= counter; i++)
{
if ((int)(number / Math.pow(10, (counter - i))) % i == 0 && check)
{
check = true;
}
else
{
check = false;
}
}
return check;
}
The first problem is that you are modifying the value of the number you are trying to check. So, if your method is called with 149, then after the while loop to count the digits, its value will be 1. So, you are always going to find that it is 'unfriendly'. Assuming you fix this so that number contains the number you are checking. Try this instead of your 'for' loop:
while ( counter && !( ( number % 10 / counter ) % counter ) )
{
number = number / 10;
counter--;
}
It works by taking the last digit of your number using the modulus or remainder operator and then divides this by the digit position and checks that the remainder is zero. If all is good, it decrements the counter until it reaches zero, otherwise it terminates before counter is zero.
Try something like this (change your isFriendly() method):
public static boolean isFriendly(int number)
{
String numberAsString = String.valueOf(number); //Convert the int as a String to make it easier to iterate through
for(int i = 0; i < numberAsString.length(); i++) {
int currentDigit = Character.getNumericValue(numberAsString.charAt(numberAsString.length() - i - 1)); //Iterate over the number backwards
System.out.println(currentDigit); //Print the current digit
if(currentDigit % (i + 1) != 0) {
return false;
}
}
return true;
}
The easy way is to convert to string and then check if it is friendly:
public static boolean isFriendly(int number)
{
String num = Integer.toString(number);
for (int i = 0, dividedBy = 1; i < num.length(); i++, dividedBy++)
{
String numToCheck = "";
for (int j = 0; j <= i; j++)
{
numToCheck += num.charAt(j);
}
if (Integer.valueOf(numToCheck) % dividedBy != 0) {
return false;
}
}
return true;
}

I can't figure out my error in my PrimeGenerator

In the output, I get a 9 where I should be getting an 11!
This occurs after the fifth call to nextPrime(). Every other output is correct except for the 5th one! I have been struggling to determine my error for a few hours now. Sorry if my code is sloppy, this is the way my mind figured out the problem! It was a requirement to use the flag controlled loop.
public class PrimeGenerator
{
private int num = 2;
public PrimeGenerator()
{
}
public int nextPrime()
{
boolean done = false;
for (int n = num; !isPrime(num); n++)
num = n;
if (isPrime(num))
{
done = true;
}
if (done)
{
int prime = num;
num++;
return prime;
}
return num;
}
public static boolean isPrime(int n)
{
boolean result = true;
for (int i = 2; n % i == 0 && i < n; i++)
result = false;
if (n == 2)
result = true;
return result;
}
}
My Tester just calls the nextPrime() method and prints the result.
You get 9 instead of 11 because you have mistake in method isPrime
public static boolean isPrime(int n)
{
boolean result = true;
for (int i = 2; n % i == 0 && i < n; i++)
result = false;
if (n == 2)
result = true;
return result;
}
Look for number 9.
first iteration: i = 2, result = true
n % i => 9 % 2 = 1, so your loop stops before first iteration and result didn't changed.
Try to change method isPrime (Updated as commented #John in comments)
public static boolean isPrime(int n)
{
if( n % 2 == 0 ) {
return false;
}
double root = Math.sqrt(n);
for ( int i = 3; i < root; i+=2 ) {
if( n % i == 0 ) {
return false;
}
}
return true;
}
Your nextPrime method returns num whether or not it is prime. Your code is effectively:
if(isPrime(num))
return num;
}
return num;
So the main problem with your code here is the method for checking if a number is prime. According to number theory, you just need to check that the given number is not divisible by any number between 2 and the root of the given number you want to determine is prime. More formally, if you want to check if a number n is prime, you need to check that n is not divisible by any number between 2 and sqrt(n).
An updated method using this number theory fact is below:
public static boolean isPrime(int n)
{
int root = (int)Math.sqrt(n);
for (int i = 2; i <= root; i++) {
if(n % i == 0) {
return false;
}
}
return true;
}
With this your determination of the prime number would be correct and would be much faster. There are even faster ways of determining primes and generating primes like sieve's algorithm.

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

Categories