I'm trying to write a method (specifically using recursion) that would return the number of even digits in a natural number. I'd like to do so with a return type of NaturalNumber in order to gain more familiarity with it. Can someone point me in the right direction?
//private static NaturalNumber countEvenDigits(NaturalNumber num)
//initalize a NaturalNumber--count--to zero
//while loop with condition that the num is not 0
//initialize a NaturalNumber--k--to num.divideBy10 so that it is equal to the last digit in the natural number
//if statement-- k mod 2 is equal to 0
//increment the NaturalNumber count
//end if statement
//call this function recursively
//end while statement
//return count
However my current implementation just returns 0, what am I thinking about in a wrong way?
First if all, you posted this in Java, so I guess natural number is Integer (or int primitive)
Then your function needs to have a check in the beginning if the function call "end requirement" is fulfilled (number != 0).
If your number is != 0, you actually do the check if it is even or odd. After this check, you need to remember that (count++) and add the return value of the recursive method call onto your count, but with the last digit removed, because you checked that in this call already. (count += countEvenDigits(naturalNumber/10)). This should call itself as long as there are more digits and finally, it will get into the initial if() that exits.
/** http://stackoverflow.com/q/36085564/6077352 */
public class NaturalNumber {
public static void main(String[] args) {
int naturalNumber = 123456789;
System.out.println(countEvenDigits(naturalNumber));
}
private static int countEvenDigits(int naturalNumber) {
int count = 0;
if (naturalNumber != 0) {
if (naturalNumber % 2 == 0) {
count = count + 1;
}
count = count + countEvenDigits(naturalNumber / 10);
}
return count;
} }
Example output:
4
Related
I am new to JAVA programming and I am having hard time doing this lab
import java.util.*;
public class FindPrimes
{
private static ArrayList<Integer> myList = new ArrayList();
//post: returns true if value is a prime number
public static boolean isPrime(int value)
{
if(value < 2 || value % 2 == 0)
return false;
if(value == 2)
return true;
for (int i = 3; i * i <= value; i += 2)
if (value % i == 0)
return false;
return true;
//temporary return so program compiles
}
//post: returns the index of the first non-prime number in myList.
// returns -1 if all numbers are prime
private static int findNotPrime()
{
for(int i=0; i<myList.size(); i++){
if(!isPrime(myList.get(i)))
return i;
}
/*ex: [60] will return 0
[2,30] will return 1
[2,2,15] returns 2
[2,2,3,5] returns -1
*/
return -1; //temporary return so program compiles
}
//post: returns the smallest factor of a number
private static int findSmallestFactor(int num)
{
for (int i = 2; i*i<= num; i++) {
if (num % i == 0)
return i;
}
/* ex:findSmallestFactor(8) -> 2
findSmallestFactor(9) -> 3
findSmallestFactor(7) -> 7
*/
return -1; //temporary return so program compiles
}
//post: recursive method that places the prime factorization into myList
//
private static void generateList()
{
//generateList();
int var = findNotPrime();
if(var != -1){
int n = findSmallestFactor(myList.get(var));
myList.set(var, n);
myList.add(myList.get(var)/n);
generateList();
}
}
/* Hint: Check the list to find the first non-prime factor.
If all the numbers are prime, you are done.
Otherwise, * find the smallest factor of the first non-prime and its cofactor.
* replace the first non-prime with its smallest factor and add the cofactor to the end
* repeat the whole process */
//post: calcualtes the prime factorization of number and returns the list containing factors
public static ArrayList<Integer> calculateFactors(int number)
{
/* place number in myList, generate the prime factorizations and return the list.*/
myList.add(new Integer(number));
//System.out.println(myList);
generateList();
return myList;
}
public static void main(String[] arg)
{
System.out.println(8 + ":" + calculateFactors(8));
myList.clear();
System.out.println(60 + ":" + calculateFactors(60));
myList.clear();
System.out.println(75 + ":" + calculateFactors(75));
}
}
The error code I get is
"Exception in thread "main" java.lang.StackOverflowError"
I have tested all the methods and they all seem to be working. I don't know why this happens.
You call generateList inside itself, causing an infinite recursion thus your stack overflows.
Don't know if you have figured out your task yet. But I did this task since it seemed like fun and since I've never done it before and.
What is the rules for answering a thread the asking person has solved already? Well.. it's easier to get forgiveness than permission...
The problem is mainly in generateList where you don't "save" a temp variable. This can be solved like this:
if(var != -1){
int temp=myList.get(var);
int n = findSmallestFactor(temp);
myList.set(var, n);
myList.add(temp/n);
generateList();
}
Other than that you have to make a small change in isPrime method. For instance if you check if 2 is a prime it will say no, when in fact 2 is a prime number.
I was writing a recursive algorithm to calculate Fibonacci numbers in Java as part of a programming 101 course. This is the code:
public class Fib {
public static void main(String[] args) {
Fib fib = new Fib();
}
public Fib() {
int end = 9;
long[] nums = new long[2];
printFib(0, end, nums);
}
private void printFib(int i, int end, long[] nums) {
while(i < end) {
if(i == 0 || i == 1) {
nums[i] = 1;
System.out.println("1");
} else {
long fib;
fib = 0;
fib += (nums[0] + nums[1]);
nums[0] = nums[1];
nums[1] = fib;
System.out.println(fib);
}
i++;
printFib(i, end, nums);
}
}
}
As I was stepping through the program it was working as intended until i became equal to end, the variable telling the printFib method how many Fibonacci numbers it should print out. When ì was equal to end while(i < 1) returns false as expected and the program go to the last }, now you'd(me)
expect the program to return the constructor from which I initially called the function and the program should exit, this not the case. The program goes back to the while statement and somehow evaluates to false again. Then it does the same thing again except the second time it decreases i by 1(what?!) and then proceeds to the else clause when it reaches the if statement. It then does the same thing over and over alternating the amount it subtracts from i between 1 and 2. I've asked my teacher about this and he was unable to explain it.
The program works fully like I intended if I replace the while with an if so maybe there is something about while that I don't know.
Edit
So I realize now that each time the method is called i has a different value which is stored and when the method exits and i = end the program goes back to the previous calls where i had a different value.
You implemented an iterative algorithm to calculate Fibonacci series. That's what the while loop does. There is no point in making the recursive call - printFib(i, end, nums) - at the end.
If you intended a recursive implementation, the entire while loop is not needed.
This code doesn't look right to me.
I would recommend that you not print from your method. Return a value to the main and let it print.
Your recursive method should not have a while loop in it. That's iteration - exactly what you're trying to avoid here.
Your method should have a stopping condition and a call to itself. That's not what you're doing.
Think about it like this:
/**
* Recursive Fibonnaci
* User: mduffy
* Date: 2/11/2015
* Time: 8:50 AM
* #link http://stackoverflow.com/questions/28455798/strange-behavior-in-recursive-algorithm/28455863#28455863
*/
public class Math {
private static Map<Integer, Integer> memo = new ConcurrentHashMap<Integer, Integer>();
public static void main(String [] args) {
for (String arg : args) {
int n = Integer.valueOf(arg);
System.out.println(String.format("n: %d fib(n): %d", n, fibonnaci(n)));
}
}
public static int fibonnaci(int n) {
if (n < 0) throw new IllegalArgumentException("index cannot be negative");
int value = 0;
if (memo.containsKey(n)) {
value = memo.get(n);
} else {
if (n <= 1) {
value = n;
} else {
value = fibonnaci(n-1)+fibonnaci(n-2);
}
memo.put(n, value);
}
return value;
}
}
Basicly this is happening because i would guess that you are thinking of i as an reference which will influence the basic callings of the Fibunacci method calling the sub Fibunacci method. This will finally lead way to many calls of the fibunacci method.
in my eyes the loop doesn´t make sense in your recursive way of solving it.
I'm trying to create a Java program that converts a String into an Integer recursively. This is currently what I have but it gives me an error, "Exception in thread "main" java.lang.NumberFormatException". The method is supposed to take in a number in the form of a string then iterate through each position. Through each iteration it turns the single number into a integer and adds it to x. By the end of it x is suppose to have the String number in integer form.
import java.util.Scanner;
public class Problem{
public static int x=0;
public static int integer;
public static int intconvert(String numb,int index,int times){
if(index==numb.length()){
return x;
}
else{
integer=Integer.parseInt("numb.charAt(index)"); //
x+=integer*times; //add int and multiply it
return intconvert(numb, index++, times*10); //
}
}
public static void main(String[] args){
Scanner scan=new Scanner(System.in);
System.out.print("Enter the String digit: ");
String number=scan.nextLine();
intconvert(number, 0, 1);
/* System.out.println(number.charAt(0));
System.out.println(number.charAt(1));
System.out.println(number.charAt(2));*/
}
}
Even if the method was correct, i.e:
public static int intconvert(String numb, int index, int times) {
if (index == numb.length()) { return x; }
integer = Integer.parseInt(String.valueOf(numb.charAt(index))); //
x += integer * times; // add int and multiply it
return intconvert(numb, index++, times * 10); //
}
You'll still get an StackOverFlow exception, because you of the way you increment your x, it will never enter the stopping condition.
If I understood what you wanted to do, the solution is:
public class Cenas {
public static int x = 0;
public static int integer;
public static int intconvert(String numb, int index, int times) {
integer = Integer.parseInt(Character.toString(numb.charAt(index))); //
x += integer * times; // add int and multiply it
if (index == 0) { return x; }
return intconvert(numb, --index, times * 10); //
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the String digit: ");
String number = scan.nextLine();
System.out.println(intconvert(number, number.length() - 1, 1));
}
Start at the algarism with the less weight and work your way to the beggining index, also you were missing the print statement at your main call.
Because you are incrementing your "times" 10 times by each iteration you must start ate the last index of the string.
Example:
123 = 1 * 100 + 2 * 10 + 3 * 1
Your problem was not recursion but the algorithm you were using.
The line
integer=Integer.parseInt(numb.charAt(index));
won't work, because charAt() returns a char, and parseInt expects a String. Try converting that char into a String with Character.toString(c):
Integer.parseInt(Character.toString(numb.charAt(index)))
Add
integer = Integer.parseInt(numb.substring(index, index + 1)); //
index++;
Instead of:
integer=Integer.parseInt("numb.charAt(index)");
And remove ++ of index++ from return intconvert(numb, index++, times * 10); its not increase passed index.
Numbers are sequential in their ascii values, so in order to turn your char into an int, you could simply do:
int integer = numb.charAt(index) - '0';
all that is left is to ensure that integer is between bounds and your function should work just fine.
by the way, I would remove the static global variables. If you simply pass them as parameters instead, your solution will be "pure", as in side-effect free or referentially transparent
Try changing
integer=Integer.parseInt("numb.charAt(index)");
into
integer=Integer.parseInt(numb.substring(index, index + 1));
The original line tries to find a number within the string "numb.charAt(index)", which doesn't contain any numbers.
Also, change index++ to index + 1 or even ++index, since index++ has no effect in this case (it only increments index after it's been used, and just before it goes out of scope.
I have an assignment introducing Recursion in Java and I am running into a roadblock. The assignment requires a recursion method to output a number of lines of a number of asterisks depending on the integer value passed to it. For example, if 4 is passed in as variable n, the output would have a first line of one asterisk, next line 2 asterisks, next 3 asterisks, next 4, then 4, 3, 2, & 1 going down.
I have been able to complete the first half of the output (not sure if it is optimal though), but have no clue how to get the method to reverse back down. This is all to be done in one method call with a variable (n) passed to the method.
Here is the method I have so far:
public static void myMethod(int n)
{
if (n <= 1) {
System.out.print("*");
} else {
myMethod(n - 1);
for (int i = 0; i < n; i++) {
System.out.print("*");
}
}
System.out.print("\n"); // new line
}
It is called from main with this:
myMethod(n);
So what I have is a for loop that will print an asterisk on the same line 'n' times. After the for loop it proceeds to the next line and cycles, changing n. But I have no idea how to get it to reverse.
My method prints from the method. My instructor showed me a sample version passing 2 variables (n) and a null string.
public static String myMethod(int n, String displayStr) {
String currentStr = "";
for (int i = 0; i < n; i++)
currentStr += "*";
currentStr += "\n";
if (displayStr == null){
return myMethod((n - 1), currentStr);
} // end base case
else if (n > 0){
return myMethod((n - 1), (currentStr + displayStr + currentStr));
}
else {
return displayStr;
}
} // end recursion method myMethod
His version prints from main using the following code line:
System.out.println(myMethod(n, null));
I have tried his version and it prints the triangle on it's side but the largest line only prints once instead of twice. I have spent all day trying to alter his to add in a duplicate line in the middle and am starting to think it isn't possible.
Any help would be GREATLY appreciated. I am at a complete standstill with this.
Change the method signature to public static void myMethod(int n, boolean reversed) where reversed is initialized to false but flips to true when you print n asterisks. Inside the method, reverse your logic if reversed is true.
You basically just need to print out the current row, then do the recursive call, then print the row again. That way, you get the stack buildup on the way up, and then again on the way down.
Here is an example that uses 2 parameters, one being the max length and the other being the iterator for the recursion.
// bootstrap method to start the recursion
public static void myMethod(int length)
{
myMethod(length, length);
}
public static void myMethod(int length, int i)
{
if (i > 0)
{
int rowLength = length - i + 1;
printRow(rowLength, '*');
myMethod(length, i - 1);
printRow(rowLength, '*');
}
}
public static void printRow(int length, char symbol)
{
for (int i = 0; i < length; i++)
System.out.print(symbol);
System.out.println();
}
Because the output counts up (not *down to zero), you must pass in the number of asterisks to print and the maximum number, so the terminating condition can be established.
Further, the pseudo code for your method is:
if n > max return (terminating condition)
print n asterisks
recursively call with n + 1
print n asterisks
A great deal of code simplification can be achieved if you pass in not the current length to print, but the String of asterisks, so your (private) recursive method could be simply:
private static void myMethod(int n, String s) {
if (s.length() < n) return;
System.out.println(s);
myMethod(n, s + "*");
System.out.println(s);
}
And your public method, which sets up the initial conditions, is then:
public static void myMethod(int n) {
myMethod(n, "*");
}
IMHO an elegant implementation with good code density.
A method, printStars(j), is available that returns a string -- a row of j asterisks. I need to write a method that recursively prints a triangle of n rows of asterisks. The first row needs to have one *, the second have two *s, etc. No iterative loops can be used (so no while, do-while, or for).
The code to do it backwards is simple enough:
public void printTriangle(int n) {
if(n >= 1) {
printStars(n));
printTriangle(n - 1);
}
}
My code thus far for the above but reversed is below. It is incorrect as i is reset to 1 in each loop. I'm just not sure how to go about it. I can only use a one-parameter function.
public void printTriangle(int n) {
int i = 1;
if(i <= n) {
printStars(i);
printTriangle(i + 1);
}
}
Just first recur, then print the line:
public void printTriangle(int n) {
if(n > 1) {
printTriangle(n - 1);
}
System.out.println(makeStars(n));
}
So the smaller triangle is printed first, and then the longer line appended.
static int i = 1;
This will ensure that i retains its value between calls to the function.
It is initialized to 1 the first time, and any changes made to the variable will persist across calls.
EDIT: As the comment says, this isn't the right way. Daniel Fischer's solution is better.
Pass the maximum value of i as a second parameter to limit the number of lines to print i.e. the maximum value for i.
Maybe a two parameters function:
public void printTriangle(int i, int n) {
if(i <= n) {
System.out.println(printStars(i));
printTriangle(i+1, n);
}
}