Here are my instructions:
Write a recursive method called printStar(int n) which will print the following when n=4:
****
***
**
*
*
**
***
****
This is what I did so far:
public class Stars{
public static void main (String[] args){
printStars(4);
}
public static void printStars(int count){
if (count==0){
System.out.println("");
}
else{
System.out.print("*");
printStars(count-1);
}
}
}
My attempt only prints one line of the given number of stars. I don't know how to print multiple lines with only one call of the method. Any help is appreciated.
This one uses tail recursion, is split into helper function, and uses loop only to get the character as required.
public class JavaR {
public static void main(String[] args) {
System.out.println(star(4, new StringBuilder()));
}
public static StringBuilder star(int times, StringBuilder builder) {
return getStars(times, builder, times);
}
public static StringBuilder getStars(int currentIteration, StringBuilder builder, int times) {
if (currentIteration < -1 * times) return builder;
else if (currentIteration != 0) {
builder.append(getNTimes(Math.abs(currentIteration)));
return getStars(currentIteration - 1, builder, times);
} else {
return getStars(currentIteration - 1, builder, times);
}
}
public static String getNTimes(int count) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < count; i++) {
builder.append("*");
}
return builder.append("\n").toString();
}
}
Your program is incorrect, see the below program and analyze it -
public class Stars{
public static void main (String[] args){
printStars(4);
}
public static void printStars(int count){
if (count==0){
// System.out.println("");
}
else{
int tempCount = count;
while(tempCount>0){
System.out.print("*");
tempCount--;
}
System.out.println();
printStars(count-1);
while(tempCount<count){
System.out.print("*");
tempCount++;
}
System.out.println();
}
}
}
Explanation - I am using two while loops to print stars, first to print the start in asc order and second to print in reverse order. Using variable tempCount to get the current counter.
Try this
public static void printStars(int count){
if (count == 0){
return;
}
printStarNTimes(count);
printStars(count-1);
printStarNTimes(count);
}
private static void printStarNTimes(int n) {
for (int i = 0; i < n; i++) {
System.out.print("*");
}
System.out.println();
}
Logic is in printing star count times in the current call and when the recursive call returns.
The method needs information about the max number of *, as well as direction (is number of * increasing or decreasing)
Since the requested method signature includes only one argument, you have a few alternatives to define the additional needed information:
Use a partially recursive method like in this and this answers, or use a helper method:
public static void printStars(int count){
printStars(count, count, -1);
}
public static void printStars(int count , int max, int increment){
for(int i =0; i< count; i++) {
System.out.print("*");
}
count += increment;
if(count ==0 ) { //lower limit reached
increment = -increment;
}else {
System.out.println("");
}
if (count > max){ //upper limit reached
return;
}
printStars(count, max, increment);
}
Related
I've been doing a MOOC.fi Java course and it comes along quite well, except the Christmas Tree part. It works as intended in the output, but the system won't accept it and I don't know why.
I get this error:
when printTriangle(1) was called, wrong amount of lines was printed expected:<1> but was:<2>
Here's the code:
public class AdvancedAstrology {
public static void printStars(int number) {
for(int i = 0; i < number; i++){
System.out.print("*");
}
System.out.println();
}
public static void printSpaces(int number) {
while(number > 0){
System.out.print(' ');
number--;
}
}
public static void printTriangle(int size) {
int star = 0;
while(size > 0){
printSpaces(size--);
printStars(star++);
}
}
public static void christmasTree(int height) {
int h = height -1;
int stand = height - 2;
int s = 1;
while(height > 0){
printSpaces(h);
printStars(s);
s+=2;
h--;
height--;
}
printSpaces(stand);
printStars(3);
printSpaces(stand);
printStars(3);
}
public static void main(String[] args) {
// The tests are not checking the main, so you can modify it freely.
printTriangle(5);
System.out.println("---");
christmasTree(4);
System.out.println("---");
christmasTree(10);
}
}
You're doing post increment, that's why in star is being passed as 0 in first iteration.
public static void printTriangle(int size) {
int star = 0;
while(size > 0){
printSpaces(size--);
printStars(star++); //Here. change it to ++star
}
}
i have a question where i need to do a recursive function getting int and doing star pattern of a square like if i insert 4 into the function it will give me:
****
****
****
****
so i made this recursion and i want to shrink my idea into one function what can you suggest to improve my design, thanks.
static int count = 0;
public static void rect(int num){
if(count<=0)
return;
if(count !=0 && num>0){
for(int i =0; i<num;i++){
System.out.print('*');
}
System.out.println();
count--;
rect(num);
}
}
public static void SetCount(int num){
count = num;
rect(num);
}
public static void main(String[] args) {
int i = 6;
SetCount(i);
}
You can eliminate the SetCount method and the second if check, something like this would work as well :
static int count = 0;
public static void rect(int num) {
if (count <= 0)
return;
for (int i = 0; i < num; i++) {
System.out.print('*');
}
System.out.println();
count--;
rect(num);
}
public static void main(String[] args) {
count = 4;
rect(count);
}
One argument, the size of the square. No external variables:
class Homework {
public static void square(int side) {
if (side > 0) {
for (int i = 0; i < side; i++) {
square(-side);
}
} else if (side < 0) {
System.out.print('*');
square(side + 1);
} else {
System.out.println();
}
}
public static void main(String[] args) {
square(5);
}
}
Your solution, and others offered so far, are all recursive on the rows of the square and iterative on the columns. This solution inverts that -- it's recursive on the columns and iterative on the rows.
OUTPUT
> java Homework
*****
*****
*****
*****
*****
>
import java.util.*;
import java.lang.*;
import java.io.*;
class Check{
static void rect(int num,int count){
if(count<=0)
return;
if(count !=0 && num>0){
for(int i =0; i<num;i++){
System.out.print('*');
}
System.out.println();
count--;
rect(num,count);
}
}
public static void main(String[] args) {
int i = 6;
rect(i,i);
}
}
Instead of using a class variable count and setting it again and again. Use two paramters for the recursive function. "num" to print stars num times in a single row and "count" to keep track of number of rows.
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
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;
}
}
I am a new member here, and I am also a beginner in JAVA. The thing that seems the most abstract to me is recursion, and so I have some difficulties finishing a program that should have this output if we write 3 for example:
1
12
123
12
1
Or if we write 5 for example it should print out this:
1
12
123
1234
12345
1234
123
12
1
And I can do this program with for loop, but I have to use recursion, and here is what I have done so far:
public class Aufgabe3 {
private static void printSequenz(int n) {
if(n<1){
return;
}
printMany(n);
printSequenz(n-1);
}
private static void printMany(int n){
for(int i=1;i<=n;i++){
System.out.print(i);
}
System.out.println();
}
public static void main(String[] args) {
printSequenz(5);
}
}
I would be really happy if someone would help me :).
You need to implement two recursive functions:
void printLoToHi(int n)
{
if (n < 1)
return;
printLoToHi(n-1);
printMany(n);
}
void printHiToLo(int n)
{
if (n < 1)
return;
printMany(n);
printHiToLo(n-1);
}
Then, you need to call them sequentially:
printSequenz(int n)
{
printLoToHi(n);
printHiToLo(n-1); // -1 in order to avoid printing the highest twice
}
Or in a more "symmetrical manner":
printSequenz(int n)
{
printLoToHi(n-1); // print lowest to second highest
printMany(n); // print the highest
printHiToLo(n-1); // print second highest to lowest
}
You could do it like this:
private static void printSequenz(int n) {
printSequenz(1,n, true);
}
private static void printSequenz(int current, int total, boolean goingUp) {
if(!goingUp && current<1){
return;
}
printMany(current);
if(current+1>total){
goingUp=false;
}
if(goingUp){
printSequenz(current+1,total,goingUp);
} else {
printSequenz(current-1,total,goingUp);
}
}
private static void printMany(int n) {
for (int i = 1; i <= n; i++) {
System.out.print(i);
}
System.out.println();
}
public static void main(String[] args) {
printSequenz(5);
}
public class Test {
public static void main(String args[]) {
int seq = 6;
for(int i=1; i<=seq; i++) {
System.out.println("");
int low =seq-(seq-i);
printIncreasing(i,low);
}
for(int i=seq-1; i>=1; i--) {
System.out.println("");
int low = seq-i;
printDecreasing(i,low);
}
}
public static void printIncreasing(int high, int low) {
for(int i = 1; i<=high;i++ ) {
System.out.print(i);
}
}
public static void printDecreasing(int high, int low) {
for(int i = 1; i<=high;i++ ) {
System.out.print(i);
}
}
}