This question already has answers here:
What is a StackOverflowError?
(16 answers)
Closed 7 years ago.
I am trying to solve a problem which asks to find the smallest prime palindrome, which comes after a given number which means that if the input is 24, the output would be 101 as it is the smallest number after 24 which is both prime and a palindrome.
Now my code works perfectly for small values but the moment I plug in something like 543212 as input, I end up with a StackOverFlowError on line 20, followed by multiple instances of StackOverFlowErrors on line 24. Here is my code :
package nisarg;
import java.util.Scanner;
public class Chef_prime_palindromes {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long num = input.nextLong();
isPalindrome(num + 1);
}
public static boolean isPrime(long num) {
long i;
for (i = 2; i < num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
public static void isPalindrome(long num) {
String word = Long.toString(num);
int i;
for (i = 0; i < word.length() / 2; i++) {
if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
isPalindrome(num + 1);
}
}
if (i == word.length() / 2) {
if (isPrime(num)) {
System.out.println(num);
System.exit(0);
} else {
isPalindrome(num + 1);
}
}
}
}
All shown exiting solutions use recursion and have the problem that at some point they will reach the point where a StackOverflowException will occur.
A better solution which would also be parallelizable would be to change it into a loop.
It could be something like:
package nisarg;
import java.math.BigInteger;
import java.util.Scanner;
import java.util.concurrent.CopyOnWriteArrayList;
public class Chef_prime_palindromes {
private static final CopyOnWriteArrayList<BigInteger> PRIMESCACHE
= new CopyOnWriteArrayList<>();
public static void main(String[] args) {
try (Scanner input = new Scanner(System.in)) {
BigInteger num = new BigInteger(input.nextLine());
initPrimes(num);
for (num = num.add(BigInteger.ONE);
!isPrimePalindrome(num);
num = num.add(BigInteger.ONE));
System.out.println(num.toString());
}
}
private static void initPrimes(BigInteger upTo) {
BigInteger i;
for (i = new BigInteger("2"); i.compareTo(upTo) <= 0 ; i = i.add(BigInteger.ONE)) {
isPrime(i);
}
}
public static boolean isPrimePalindrome(BigInteger num) {
return isPrime(num) && isPalindrome(num);
}
// could be optimized
public static boolean isPrime(BigInteger num) {
for (int idx = PRIMESCACHE.size() - 1; idx >= 0; --idx) {
if (num.mod(PRIMESCACHE.get(idx)).compareTo(BigInteger.ZERO) == 0) {
return false;
}
}
if (!PRIMESCACHE.contains(num)) {
PRIMESCACHE.add(num);
}
return true;
}
public static boolean isPalindrome(BigInteger num) {
String word = num.toString();
int i;
for (i = 0; i < word.length() / 2; i++) {
if (word.charAt(i) != word.charAt(word.length() - i - 1)) {
return false;
}
}
return true;
}
}
A new String object is created in each recursive call and placed onto stack (the place where all variables created in methods are stored until you leave the method), which for a deep enough recursion makes JVM reach the end of allocated stack space.
I changed the locality of the String object by placing it into a separate method, thus reducing its locality and bounding its creation and destruction (freeing of stack space) to one recursive call.
package com.company;
import java.util.Scanner;
public class Chef_prime_palindromes {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long num = input.nextLong();
isPalindrom(num + 1);
}
public static boolean isPrime(long num) {
long i;
for (i = 2; i < num; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
private static void isPalindrom(long num) {
for (; ; ) {
if (isPalindrome(num)) {
if (isPrime(num)) {
System.out.println(num);
System.exit(0);
} else {
num++;
}
} else {
num++;
}
}
}
public static boolean isPalindrome(long num) {
String string = String.valueOf(num);
return string.equals(new StringBuilder(string).reverse().toString());
}
}
First thing you should be aware of is the fact that your resources are limited. Even if your implementation was precise and all recursive calls were correct, you may still get the error. The error indicates your JVM stack ran out of space. Try to increase the size of your JVM stack ( see here for details).
Another important thing is to look for the distribution of prime and palindrome numbers. Your code runs by testing every num+1 against palindrome property. This is incorrect. You test for palindrome only when the number is prime. This will make the computation much much easier (and reduce recursive calls). I have edited your code accordingly and got the closest palindrome number after 543212 (1003001) . Here it is:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
long num = input.nextLong();
//isPalindrome(num+1);
nextPrimePalindrome(num+1);
}
public static void nextPrimePalindrome(long num)
{
boolean flag=true;
while(flag)
{
if(isPrime(num))
if(isPalindrome(num))
{
System.out.println(num);
flag=false;
}
num++;
}
}
public static boolean isPrime(long num){
long i;
for(i=2;i<num;i++){
if(num%i == 0){
return false;
}
}
return true;
}
public static boolean isPalindrome(long num)
{
String word=Long.toString(num);
for(int i=0;i<word.length()/2;i++)
if(word.charAt(i)!=word.charAt(word.length()-i-1))
return false;
return true;
}
}
Related
I'm trying to create a code where the user inputs a number, and the program returns whether the number is prime or not. This is my first code in Java, so I'm still learning! The code compiles but when I run it, it doesn't have an option to input.
import java.util.Scanner;
public class Prime {
public void main(String[] args)
{
Scanner reader = new Scanner(System.in);
int number = reader.nextInt();
if (isPrime(number) == true)
{
System.out.println(number+"is a prime number");
}
else
{
System.out.print(number+"is not a prime number");
}
}
public boolean isPrime(int number)
{
int counter = 0;
boolean result = true;
for (int n = 2; n <= 9; n++) {
if (number % n == 0 && n != number) {
counter = 1;
} else {
counter = 2;
}
if (counter == 1){
result = true;
}
else result = false;
}
return (result);
}
}
The issue here is regarding the main method which is missing the static keyword, so there is no app entry without that.
Please change the main method from
public void main(String[] args)
To
public static void main(String[] args)
Also, add static to the isPrime method in order to everything work.
This problem arised because of no Entry point was found by the java compiler
Code Snippet
Run Code Here
import java.util.Scanner;
public class Prime {
public static void main(String[] args)
{
Scanner reader = new Scanner(System.in);
int number = reader.nextInt();
if (isPrime(number) == true)
{
System.out.println(number+"is a prime number");
}
else
{
System.out.print(number+"is not a prime number");
}
}
static public boolean isPrime(int number)
{
int counter = 0;
boolean result = true;
for (int n = 2; n <= 9; n++) {
if (number % n == 0 && n != number) {
counter = 1;
} else {
counter = 2;
}
if (counter == 1){
result = true;
}
else result = false;
}
return (result);
}
}
The program works fine for small numbers but as soon as i take a big number like this it doesn't work
here is my code
public class Main {
public static void main(String[] args) {
long no=600851475143L,i;
int result=0;
for(i=(no/2);i>=2;i--){
if(no%i==0){
if(checkPrime(i)){
System.out.println("Longest Prime Factor is: " + i);
break;
}
}
}
}
private static boolean checkPrime(long i){
for(long j=2L;j<=(int)Math.sqrt(i);j++){
if(i%j==0)
return false;
}
return true;
}
}
to assign long variable value we does not require write L at last on value Remove L.
It will take time to display the answer. Just try with small number(1000000 ) almost 10 to 15 min for above code.
Try this
public class Main {
public static void main(String[] args) {
//long no=600851475143L,i;
System.out.println(largestPrimeFactor(600851475143L));
}
public static int largestPrimeFactor(long number) {
int i;
for (i = 2; i <= number; i++) {
if (number % i == 0) {
number /= i;
i--;
}
}
return i;
}
}
[1]https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
I am a beginner trying to learn Java so I started off by doing the famous FizzBuzz project. This project requires the user to make an instance of a FizzBuzz class and pass in a value. Now the code, which is in another Java Class, reads the number the user passes in and makes a list of all the numbers between 1 and the number the user passed in. I was able to complete this until I got to the next exercise which required me to create 3 private boolean methods (see below):
public class FizzBuzzRunner
{
private boolean fizz(int num)
{
return num % 3 == 0;
}
private boolean buzz(int num)
{
return num % 5 ==0;
}
private boolean fizzbuzz(int num)
{
return num % 3 ==0 && num % 5 == 0;
}
public void fizzBuzz(int num)
{
for (int i = 1; i < num + 1; i++)
{
if (fizzbuzz(num))
{
System.out.println("FizzBuzz");
} else if (fizz(num))
{
System.out.println("Fizz");
} else if (buzz(num))
{
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
}
Now my code is obviously wrong. Firstly, how can I link the variable in the public method (int num) so that it's the same variable in the private methods? My second question is if the arguments inside the If statements are fine. Essentially what I want is, for example, if fizz method is true print "fizz" etc.
Pass the value if i not num
public void fizzBuzz(int num)
{
for (int i = 1; i < num + 1; i++)
{
if (fizzbuzz(i))
{
System.out.println("FizzBuzz");
}
else if (fizz(i))
{
System.out.println("Fizz");
}
else if (buzz(i))
{
System.out.println("Buzz");
}
else {
System.out.println(i);
}
}
}
I am trying to get all prime factors of a number. The for loop should work until it finds the match and it should break and jump to the next if statement which checks if number is not equal to zero.
public class Factor {
public static ArrayList <Integer> HoldNum = new ArrayList();
public static void main(String[]args){
Factor object = new Factor();
object.Factor(104);
System.out.println(HoldNum.get(0));
}
public static int Factor(int number){
int new_numb = 0;
int n=0;
for( n = 1; n < 9; n++) {
if (number % n == 0) {
HoldNum.add(n);
new_numb = number/n;
break;
}
}
System.out.println(new_numb);
if(new_numb < 0) {
HoldNum.add(new_numb);
return 1;
} else {
return Factor(new_numb);
}
}
}
There are at least three errors :
As okiharaherbst wrote, your counter is not incremented.
you start your loop at 1, so yourval % 1 always equals to 0 and new_numb is always equals to your input val, so you'll loop endlessly on 104.
new_numb will never be lesser than 0.
You asked for a recursive solution. Here you go:
public class Example {
public static void main(String[] args) {
System.out.println(factors(104));
}
public static List<Integer> factors(int number) {
return factors(number, new ArrayList<Integer>());
}
private static List<Integer> factors(int number, List<Integer> primes) {
for (int prim = 2; prim <= number; prim++) {
if (number % prim == 0) {
primes.add(prim);
return factors(number / prim, primes);
}
}
return primes;
}
}
The code is not bullet-proof, it is only a quick-and-dirty example.
Java implementation...
public class PrimeFactor {
public int divisor=2;
void printPrimeFactors(int num)
{
if(num == 1)
return;
if(num%divisor!=0)
{
while(num%divisor!=0)
++divisor;
}
if(num%divisor==0){
System.out.println(divisor);
printPrimeFactors(num/divisor);
}
}
public static void main(String[] args)
{
PrimeFactor obj = new PrimeFactor();
obj.printPrimeFactors(90);
}
}
I'm supposed to write a code which checks if a given number belongs to the Fibonacci sequence. After a few hours of hard work this is what i came up with:
public class TP2 {
/**
* #param args
*/
public static boolean ehFibonacci(int n) {
int fib1 = 0;
int fib2 = 1;
do {
int saveFib1 = fib1;
fib1 = fib2;
fib2 = saveFib1 + fib2;
}
while (fib2 <= n);
if (fib2 == n)
return true;
else
return false;
}
public static void main(String[] args) {
int n = 8;
System.out.println(ehFibonacci(n));
}
}
I must be doing something wrong, because it always returns "false". Any tips on how to fix this?
You continue the loop while fib2 <= n, so when you are out of the loop, fib2 is always > n, and so it returns false.
/**
* #param args
*/
public static boolean ehFibonacci(int n) {
int fib1 = 0;
int fib2 = 1;
do {
int saveFib1 = fib1;
fib1 = fib2;
fib2 = saveFib1 + fib2;
}
while (fib2 < n);
if (fib2 == n)
return true;
else
return false;
}
public static void main(String[] args) {
int n = 5;
System.out.println(ehFibonacci(n));
}
This works. I am not sure about efficiency..but this is a foolproof program,
public class isANumberFibonacci {
public static int fibonacci(int seriesLength) {
if (seriesLength == 1 || seriesLength == 2) {
return 1;
} else {
return fibonacci(seriesLength - 1) + fibonacci(seriesLength - 2);
}
}
public static void main(String args[]) {
int number = 4101;
int i = 1;
while (i > 0) {
int fibnumber = fibonacci(i);
if (fibnumber != number) {
if (fibnumber > number) {
System.out.println("Not fib");
break;
} else {
i++;
}
} else {
System.out.println("The number is fibonacci");
break;
}
}
}
}
you can also use perfect square to check whether your number is Fibonacci or not. you can find the code and some explanation at geeksforgeeks.
you can also see stackexchange for the math behind it.
I'm a beginner but this code runs perfectly fine without any issues. Checked with test cases hopefully it'll solve your query.
public static boolean checkMember(int n) {
int x = 0;
int y = 1;
int sum = 0;
boolean isTrue = true;
for (int i = 1; i <= n; i++) {
x = y;
y = sum;
sum = x + y;
if (sum == n) {
isTrue=true;
break;
} else {
isTrue=false;
}
}
return isTrue;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.print(checkMember(n));
}