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
Related
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;
}
My code
void printPrimes (int max) {
boolean prime;
for (int n = 2; n < max; n++){
prime = true;
double maxF;
maxF = Math.sqrt(n);
for (int f = 2; f < maxF; f++) {
if (n % f == 0) {
prime = false;
}
}
if (prime == true) {
System.out.println(n + " is prime");
}
}
}
This the result I get
4 is prime
5 is prime
6 is prime
7 is prime
8 is prime
9 is prime
10 is prime
11 is prime
what do I do to fix this issue
Debug your code. As in, take out a pen, be the computer. You answer, without running this code, what it should do. Then check what it actually does with a debugger (or sysout statements if you must). There where you find a difference, you found a bug.
For example, Math.sqrt(4), what's that? is 2 less than 2?
Change your conditional in your loop
for (int f = 2; f <= maxF; f++) { // should be <= maxf
if (n % f == 0) {
prime = false;
}
}
at least replace f < maxF with f*f <= max
Because loop maximum should be less or equals to
Math.sqrt(number)
public class Main {
public static void main(String[] args) {
printPrimes(20);
}
static void printPrimes (int max) {
for(int i=2;i<=max;i++){
if(isPrime(i)){
System.out.println(i+" is prime");
}
}
}
static boolean isPrime(int number) {
if(number < 2){
return false;
}
for(int i=2;i<=Math.sqrt(number);i++){
if(number % i == 0){
return false;
}
}
return true;
}
}
I was asked to write a program to find next prime number in an optimal way. I wrote this code, but I could not find an optimal answer to it. Any suggestions?
public static int nextPrime(int input) {
input++;
//now find if the number is prime or not
for(int i=2;i<input;i++) {
if(input % i ==0 ) {
input++;
i=2;
}
else{
continue;
}
}
return input;
}
public int nextPrime(int input){
int counter;
input++;
while(true){
int l = (int) sqrt(input);
counter = 0;
for(int i = 2; i <= l; i ++){
if(input % i == 0) counter++;
}
if(counter == 0)
return input;
else{
input++;
continue;
}
}
}
There is no need to check up on input number. It is enough to check up to the square root of a number. Sorry, I didn't remember the theorem name. Here we are incrementing the input for next prime.
The time complexity of this solution O(n^(3/2)).
#Ephraim - I've replaced the recursive code with "while" loop. It's running more faster.
int nextPrime(int M) {
while(!isPrime(++M))
// no need ++M; as I already added in the isPrime method's parameter.
return M;
}
boolean isPrime(int M) {
for(int i = 2; i <= M; i++)
if(M % i == 0)
return false;
return true;
}
#Scott Parent- I've tested the the recursive code; "while" loop and steam code (IntStream and LongStream) - the Stream's code is running slowly, very slowly.
Example:
Input value: 60000000000
Output: 60000000029
Elapsed time for recursive algorithm = 7 milliseconds
Output: 60000000029
Elapsed time for traversal algorithm = 4 milliseconds
Output: 60000000029
Elapsed time for LongStream.range(2, number).noneMatch(...) algorithm = 615825 milliseconds
If I use IntStream - the elapsed time is about 230 milliseconds for the max Integer number. It's too much slowly. The "while" loop in nextPrime(int n) is running 1-4 milliseconds for the max integer number, but usage of LongStream for 600000000000 input value - the result I couldnt see in 1 hour.
I'm running now for the 600000000000 long number:
Elapsed time for recursive algorithm = 36 milliseconds
Output: 60000000029
Elapsed time for traversal algorithm = 27 milliseconds
Output: 60000000029
Elapsed time for LongStream.range(2, number).noneMatch(...)
it's still running more than 58 minutes, but it's not finished yet.
long n = 12345;
BigInteger b = new BigInteger(String.valueOf(n));
long res = Long.parseLong(b.nextProbablePrime().toString());
System.out.println("Next prime no. is "+ res);
Generate all prime numbers up to your limit using sieve of eratosthenes. And then input your number n and search if n> prime[i] , prime[i] is the answer.
You can also do the same using recursions like this:
int nextPrime(int M) {
if(!isPrime(M)) M = nextPrime(++M);
return M;
}
boolean isPrime(int M) {
for(int i = 2; i <= Math.sqrt(M); i++)
if(M % i == 0) return false;
return true;
}
My son has written his own algorithm - in one method.
But it's written on python - you can find it here.
On Java it looks like:
static long nextPrime(long number) {
boolean prime = false;
long n = number;
while (!prime && n < number * 2) {
n++;
prime = true;
for (int i = 2; i < n; i++) {
if (n % i == 0) {
prime = false;
break;
}
}
}
return n;
}
Here I add a solution algorithm. First of all, the while loop grabs the next number to be tested within the range of number + 1 to number * 2. Then the number is sent to the isPrime method (which uses Java 8 streams) that iterates the stream to look for numbers that have no other factors.
private static int nextPrime(final int number) {
int i = number + 1;
while (!isPrime(i) && i < number * 2)
i++;
return i;
}
private static boolean isPrime(final int number) {
return number > 1 && IntStream.range(2, number).noneMatch(index -> number % index == 0);
}
Dude check this code.
isPrime() in the while loop checks for the next prime number after incrementing the current prime/non-prime number. I did used the long datatype (that's what I got as assignment).
if (isPrime(num)) {
System.out.println("Current Prime number: " + num);
} else {
long a = getNextPrime(num);
System.out.println("Next Prime:" + a);
}
public static long getNextPrime(long num) {
long nextPrime = 0;
while (true) {
num++;
boolean x = isPrime(num);
if (x) {
nextPrime = num;
break;
}
}
return nextPrime;
}
public static boolean isPrime(long num) {
if (num == 0 || num == 1) {
return false;
}
for (long i = 2; i <= num / 2; ++i) {
if (num % i == 0) {
return false;
}
}
return true;
}
This is functional way of finding next prime number.
public void printFirstNPrimes(long n) {
Stream.iterate(2, i->nextPrime(i))
.limit(n).forEach(System.out::println);
}
public static boolean isPrime(long x) {
return Stream.iterate(2, i->i+1)
.limit((long)(Math.sqrt(x)))
.allMatch(n -> x % n != 0);
}
public static int nextPrime(int x) {
return isPrime(x+1)? x+1 : nextPrime(x+1);
}
So, I was reading the first answer and saw some potential upgrades.
I made them and got a really significant improvement.
The original code could calculate 200000 prime numbers in 22.32s
With a little changes I managed to execute the same operation in 11.41s, with the same results.
Notice I executed the code on my laptop #2.50 GHz, running on IntelIJ.
public static int nextPrime(int n) {
boolean isPrime;
n++;
while (true) {
int sqrt = (int) Math.sqrt(n);
isprime = true;
for (int i = 2; i <= sqrt; i++) {
if (n % i == 0) isPrime = false;
}
if (isPrime)
return n;
else {
n++;
}
}
}
Hope you like it!
public class ClosestPrimeNumber {
static boolean isPrime(int n) {
for (int x = 2; x <= Math.sqrt(n); x++) {
if (n % x ==0) {
return false;
}
}
return true;
}
static int next_forward = 0;
static int next_backward = 0;
static int next = 0;
static int closestPrimeNumberForward(int n) {
if (isPrime(n)) {
next_forward = n;
return next_forward;
}else {
next_forward = n+1;
closestPrimeNumberForward(next_forward);
}
return next_forward;
}
static int closestPrimeNumberBackward(int n) {
if (isPrime(n)) {
next_backward = n;
return next_backward;
}else {
next_backward = n-1;
closestPrimeNumberBackward(next_backward);
}
return next_backward;
}
static int closestCompare(int forward, int backward, int num) {
return (Math.abs(num-backward) > Math.abs(num-forward) ) ? forward : backward;
}
public static void main(String[] args) {
int valor = 102;
System.out.println(closestCompare(closestPrimeNumberForward(valor), closestPrimeNumberBackward(valor), valor));
}
}
public int nextPrime(int input){
int counter;
while(true){
counter = 0;
for(int i = 1; i <= input; i ++){
if(input % i == 0) counter++;
}
if(counter == 2)
return input;
else{
input++;
continue;
}
}
}
This will return the nextPrime but cannot say is most optimal way
It is simple as it execute an infinite while loop which break when
prime number is returned.
In while is finds whether the number is prime or not
If it is prime it returns that number, if not it increment input and continue the while loop
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";
}
}
}
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