Boolean Satements - java

public class A4work
{
private static int fibonacci(int n) {
if (n <= 1) {
return n;
}
{
return fibonacci(n - 1) + fibonacci(n - 2);
}
}
private static boolean isAfibonacci(int a) {
int x = 0; //sequence number
int c = 0; //number in fib sequence
while (a <= c) {
c = fibonacci(x);
x++;
}
if (a == c) {
return true;
} else {
return false;
}
}
public static void main(String[] args) //called a method signiture
{
System.out.println("The 5th Square pyramidal number is " + isAfibonacci(3));
}
}
I think I have the code right, but it keeps on returning false. I'm using it to decide if a number is in the fib sequence or not.
Thanks for the help

When you use System.out.println("The 5th Square pyramidal number is "+ isAfibonacci(3) );, a in your isAfibonacci(); method becomes 3. Now look at your code knowing that.
while(3 <= 0) //replaced a with 3 here and c with 0 for visualization
{
...
}
A non-negative, non-zero integer will never be less than or equal to 0, therefore, will always result in false.

If your input a is 5, for example, you will have:
int c = 0; //number in fib sequence
while (a <= c) { ... }
The while loop will never run since 5 <= 0 is false. So a == c will always be false for any a greater than zero.
I think you want to stop iterating when c is greater than or equal to a, so the correct condition would be
while (c < a) { ... }

Related

Sum of first and last digit in recursion

I had a test exam in java, that almost no one have succeeded in this question and I can't figure out the solution.
The question was like this:
Find the sum of an integer last and first number. For example 1234-->5, 137-->8, 4-->8. You are only allowed to use recursion and no helper function"
I tried various things. Here is my last attempt:
public static int sumOfFirstandLastdigits(int number)
{
int lastdigit=sumOfFirstandLastdigits(number/10);
if(number/10==0)
{
return number%10;
}
return lastdigit+sumOfFirstandLastdigits(number%10);
}
Assuming the input is supposed to be non-negative:
//If n < 0, return first digit of -n
//Otherwise, return sum of first and last digits of n
int sumLastAndFirstDigit(int n) {
if (n < -9)
return sumLastAndFirstDigit(-(-n/10));
if (n <= 0)
return -n;
if (n < 10)
return n+n;
return n%10 + sumLastAndFirstDigit(-(n/10));
}
You can do this by overloading the method and passing the last digit as a second parameter to keep track of it through the recursion without changing the value (AKA Default Parameter):
public static void main(String[] args) {
System.out.println(sumDigits(3891901));
System.out.println(sumDigits(1234));
System.out.println(sumDigits(5678));
}
private static int sumDigits(int i) {
return sumDigits(i, i % 10);
}
private static int sumDigits(int i, int j) {
if (i / 10 == 0) {
return i % 10 + j;
}
return sumDigits(i / 10, j);
}
Output:
4
5
13
This thread on default parameters might help learn more as well.
Found a solution using String, not sure it's the best :
public int sumLastAndFirstDigit(Integer firstDigit, int number) {
String numberAsString = String.valueOf(number);
//Set the first digit
if(firstDigit == null) {
firstDigit = Integer.valueOf(numberAsString.substring(0,1));
//If there is only one digit in number for the first loop, then return 2 x firstDigit
if(numberAsString.length() == 1) {
return 2 * firstDigit;
}
}
//Remove the first digit to create the new number
String newNumberAsString = numberAsString.substring(1);
Integer newNumber = Integer.valueOf(newNumberAsString);
if(newNumberAsString.length() == 1) {
//When it's the last digit, sum first and last
return firstDigit + newNumber;
}
return sumLastAndFirstDigit(firstDigit, newNumber);
}
Then do :
sumLastAndFirstDigit(null,1234);
sumLastAndFirstDigit(null,137);
sumLastAndFirstDigit(null,4);
Use the sign as a flag to recognize the initial call. Only works with positive numbers, of course.
public static int sum(int value){
if(value > 0)
// initial call
return value % 10 + sum(-value);
else
// recursive call
return -value < 10 ? -value : sum(value / 10);
}
This are the 2 different solutions my professor suggested, although he said no helper (the first one is without an helper).
public static int sumFirstAndLast2(int num) {
if (num < 10 )
return num+num;
return sumFirstAndLast2(num/10) - num%100/10 + num%10;
}
public static int sumFirstAndLast(int num) {
if ( num < 10 )
return num+num;
return sumFirstAndLastHelper(num,true);
}
private static int sumFirstAndLastHelper(int num, boolean isLast) {
if ( isLast )
return num%10 + sumFirstAndLastHelper(num/10,false);
if ( num < 10 )
return num;
return sumFirstAndLastHelper(num/10,false);
}

Recursion to find last index of common digit between two ints

I'm trying to implement a method that finds the highest index of common digit between two ints like so:
a = 2224 , b = 4222 the result would be index = 2, which means the index is in reverse. I managed to find the first common digit, but I'm having trouble finding the last common digit. This the method to find the first common digit:
private static int getLowestIndexWithSameDigit(int a, int b) {
if (a < 0 || b < 0)
throw new IllegalArgumentException("Ambos os argumentos devem ser positivos: " + a + " " + b);
else {
if (a % 10 == b % 10) {
return indice;
} else if (a / 10 != 0 && b / 10 != 0) {
indice++;
return getLowestIndexWithSameDigit(a / 10, b / 10);
} else {
return -1;
}
}
}
And the method to initialize index as 0 everytime getLowestIndexWithSameDigit is used:
private static void test_getLowestIndexWithSameDigit(int a, int b) {
try {
System.out.print("getLowestIndexWithSameDigit (" + a + ", " + b + ") = ");
indice = 0;
int res = getLowestIndexWithSameDigit(a, b);
System.out.println(res);
} catch (IllegalArgumentException e) {
System.out.println("Erro: " + e.getMessage());
}
}
I was trying to adapt this method in some way, but I don't think it's adaptable to find the last common digit. Any help is appreciated.
It might be simpler to convert the ints to Strings:
//you can overload method to support other primitives
private static int getHighestIndexWithSameDigit(int a, int b) {
String aS = String.valueOf(a);
String bS = String.valueOf(b);
return getHighestIndexWithSameDigit(aS, bS);
}
//helper method to set strat index
private static int getHighestIndexWithSameDigit(String aS, String bS) {
return getHighestIndexWithSameDigit(aS, bS, 1);
}
//recursively check first letter. First index is 1 - indicates first char from left
private static int getHighestIndexWithSameDigit(String aS, String bS, int index) {
int aLength = aS.length(), bLength = bS.length();
if((aLength == 0) || (bLength == 0)) { return -1;}
if(aS.charAt(0) == bS.charAt(0)) { return index; }
//remove first letters, update index
return getHighestIndexWithSameDigit(aS.substring(1, aLength),
bS.substring(1, bLength), ++index);
}
Test by System.out.println(getHighestIndexWithSameDigit(2224 , 4222) );
Edit:
The code posted assumed that the first index is 1 (1 base), where index of value 1 indicates the first digit from left.
If you meant to use 0 base index, counting from right two of the method should change slightly :
//helper method to set start index.
private static int getHighestIndexWithSameDigit(String aS, String bS) {
return getHighestIndexWithSameDigit(aS, bS, aS.length()-1);
}
//recursively check first letter. Index 0 - indicates last char
private static int getHighestIndexWithSameDigit(String aS, String bS, int index) {
System.out.println(aS +" "+ bS);
int aLength = aS.length(), bLength = bS.length();
if((aLength == 0) || (bLength == 0)) { return -1;}
if(aS.charAt(0) == bS.charAt(0)) { return index; }
return getHighestIndexWithSameDigit(aS.substring(1, aLength),
bS.substring(1, bLength), --index);
}
Getting the lowest or the highest should only be a matter of when you stop the loop, no?
The slightly rewritten version of your code below did the trick for me at least.
private static int getDatIndex(int a, int b, boolean getDatLow) {
int indice = -1;
int index = 0;
while (a/10 != 0 && b/10 != 0) {
if (a % 10 == b % 10) {
indice = index;
// If you want the lowest common digit index: stop the loop.
if (getDatLow) {
break;
}
}
a = a/10;
b = b/10;
index++;
}
return indice;
}

Collatz Conjecture Method - Java

I am just learning to use methods in Java. I am trying to use a method to output the number of steps it takes to get to 1 using the collatz conjecture. Can anyone help me understand better how to execute the method? This is what I have so far:
public static void main(String[] args) {
collatz();
}
public static void collatz(int n) {
n = 20;
int i = 0;
if (n == 1) {
} else if (n % 2 == 0) {
n = (n / 2);
} else {
n = (3 * n + 1);
}
i++;
System.out.println(i);
}
This won't work because "i" is only going to be changed at the end of your code and you are not using recursion or any sort of loop in your code. So, even if it did compile, it won't give the right answer.
This is the recursive way that I've done for you.
public class Cycle {
static int cycle2 (int num) {
if (num == 1) {
return 0;
} else {
if (num % 2 > 0) {
return 1 + cycle2(num * 3 + 1);
} else {
return 1 + cycle2(num / 2);
}
}
}
public static void main(String[] args) {
int num = 14;
System.out.println(cycle2(num));
}
}
As I understand it you're asking about the syntax (rather than the algorithm itself), so here's another version of the above:
public static void main(String[] args) {
// collatz has to be called with a value or it won't compile
collatz(20);
}
public static void collatz(int n) {
int i = 0;
// The following has to occur inside a loop or it'll only occur once
while (n > 1)
{
// The following is what's known as "ternary form" - if the first statement is true, it'll assign the first value. Otherwise it assigns the first value.
// For example,
// int a = (1 == 2 ? 10 : 20);
// will equal 20
n = (n % 2 == 0 ?
(n / 2) : // This value will be assigned if n is even
(3 * n + 1)); // This value will be assigned if n is odd
i++;
}
System.out.println(i);
}
I know this question was asked a long time ago and i had similar problem so this is my solution:
public class Collatz {
public static void main(String[] args) {
collatz();
}
/*If you have (int n) inside method then
when you are calling collatz() you need to have
value inside parentheses-collatz(20), or do simply like I did.
Also you need while loop! It will loop n (20) untill finaly get 1.
Otherwise your code will execute only once
and you will have as a result 1 step to complete instead of 7*/
private static void collatz() {
int n = 20;
int i = 0;
while (n != 1) {
if (n % 2 == 0) {
n = (n / 2);
} else {
n = (3 * n + 1);
}
i++;
}
System.out.println(i);
}
}

Recursive method to calculate log

I did the following to calculate recursive logarithm:(b is the base of log here)
int log(int b, int n) {
if (n/b == 1) {
return 1;
} else {
return log(b, n/b) + 1;
}
}
However, it's wrong.I'm doing it from the openDSA interactive platform.The original question is the following:
For function "log", write the missing base case condition and the recursive call. This function computes the log of "n" to the base "b". As an example: log 8 to the base 2 equals 3 since 8 = 222. We can find this by dividing 8 by 2 until we reach 1, and we count the number of divisions we made. You should assume that "n" is exactly "b" to some integer power.
int log(int b, int n) {
if /* Missing base case condition */ {
return 1;
} else {
return /* Missing a Recursive case action */;
}
}
My code is incorrect.I'm getting infinite recursion.
If the format MUST be like this:
int log(int b, int n ) {
if <<enter base case>> {
return 1;
} else {
return <<enter action case>> ;
}
}
Then the safest method (that I can come up with) would be:
int log(int b, int n ) {
if (n <= b) {
return 1;
} else {
return log(b, n/b)+1 ;
}
}
A better solution in my opinion would be
int log(int b, int n ) {
if (b > n) {
return 0;
} else {
return 1 + log(b, n/b);
}
}
This returns the log base b of n rounded down to an integer, and has more consistency with inexact results than the other answer.
e.g. log(2,6)=2 ; log(2,7)=2 ; log(2,8)=3 ; log(2,9)=3
Though, it still doesn't handle things like b < 2 or cases where the result would be negative.
int log(int b, int n ) {
if (b == 1) {
return b;
} else if (n == 1) {
return 0;
} else {
return 1 + log(b, n/b);
}
}

Determine Fibonacci Number from User Input using Recursion

From my homework, I need to have the user enter a number in numeric form, and convert it to the simultaneous fibonacci number from the sequence, while using recursion.
My question is how can I make the sequence through an array but not store it, so the array can be the size of the number the user entered...
Here's some starting code I have:
import java.util.Scanner;
public class ReverseUserInput1 {
//a recursive method to reverse the order of user input
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ReverseUserInput1 reverseIt = new ReverseUserInput1(); //creates new object
System.out.print("Program to convert a number to a fibonacci number,");
System.out.print(" - press Enter after each number. ");
System.out.println("- type \'0 or 1\' to finish the program.");
System.out.print(" --Enter a number: ");
int aNum = in.nextInt();
reverseIt.reverseInput(aNum); //invokes reverseInput() method
}
public static int reverseInput() {
if(aNum == 0) {
return aNum;
}
else if(aNum == 1) {
return aNum;
}
else {
reverseInput();
}
System.out.println(aNum);
}
}
Here is one method, note that this also includes the negafibonacci sequence;
private static Map<Integer, BigInteger> fibCache =
new HashMap<Integer, BigInteger>();
public static BigInteger fib(int n) {
// Uses the following identities, fib(0) = 0, fib(1) = 1 and fib(2) = 1
// All other values are calculated through recursion.
if (n > 0) {
// fib(1) and fib(2)
if (n == 1 || n == 2) {
return BigInteger.ONE;
}
synchronized (fibCache) {
if (fibCache.containsKey(n)) {
return fibCache.get(n);
}
BigInteger ret = fib(n - 2).add(fib(n - 1));
fibCache.put(n, ret);
return ret;
}
} else if (n == 0) {
// fib(0)
return BigInteger.ZERO;
}
if (n % 2 == 0) {
return fib(-n).multiply(BigInteger.ZERO.subtract(BigInteger.ONE));
}
return fib(-n);
}
public static void main(String[] args) throws Exception {
for (int x = -8; x <= 8; x++) {
System.out.println(fib(x));
}
}
Outputs
-21
13
-8
5
-3
2
-1
1
0
1
1
2
3
5
8
13
21
I was not going to post the actual algorithm (see my comment to his question earlier), but then I saw an unnecessarily complex version being posted. In contrast, I'll post the concise implementation. Note this one returns the sequence starting with 1,1,2. Another variant starts with 0,1,1,2 but is otherwise equivalent. The function assumes an input value of 1 or higher.
int fib(int n) {
if(n == 1 || n == 2) return 1;
return fib(n-2) + fib(n-1);
}
That's all.

Categories

Resources