I've got this code
public class FiboNegativV {
int negativ(int nv) {
if (nv ==0)
return 1;
if (nv ==1)
return 2;
return negativ(nv-1) + negativ(nv-2);
}
}
Now I would like to turn the final number into negative. I've tried a few things like "nv = -nv;" But I usually got stackover when I put it before the
"return negativ(nv-1) + negativ(nv-2)" and it is unreachable when it's after this line.
You don't need function for that just do it like this:
int x *= -1;
All the other answers for some reason disregard your initial intention of a Fibbonacci sequence. But I do not understand why they do not keep the context. Your method obviously tries to do a Fibbonacci sequence with recursion yielding negative numbers.
Now I would like to turn the final number into negative.
The simplest and most intuitive way of negatinv a number is to use a unary minus operator = just add a minus before the expression (so negating x to -x). We use this only on positive numbers, so that the negative ones stay negative: (note: this is a ternary operator)
(result > 0) ? -result : result;
However the big mistake is that you do NOT handle negative numbers in the recursive method in the first place! Of course you run into stack overflow, because the recursive negative numbers are going to get lower and lower.
static int negativFib(int nv)
{
//turn negative input into positive
nv = nv < 0 ? -nv : nv;
//base cases
if (nv == 0)
return 1;
if (nv == 1)
return 2;
final int result = negativFib(nv - 1) + negativFib(nv - 2);
//turn the number into negative
return result > 0 ? -result : result;
}
Alternative algorithm
An another problem which could occur is that with big numbers, the recursion comes to a stack overflow. You could prevent this by using some other algorithm, f.e. dynamic programming. With dynamic programming Fibbonacci sequence you store the previous 2 results every time and solve the problem in iterations, instead of recursion.
If you only want to convert positive into negative then
nv = (nv > 0) ? nv * -1 : nv
if you want to convert positive to negative and negative to positive then
nv = nv * -1
Below your code will look like
public class FiboNegativ
{
public FiboNegativV(){}
int negativ(int nv)
{
return (nv > 0) ? nv*-1 : nv;
}
}
Since you want only the final number to be negative, the easiest way is to work with absolute numbers, and return negative numbers, as per the following:
public class FiboNegativV {
int negativ(int nv) {
return (nv == 0) ? -1 :
(nv == 1) ? -2 :
-(Math.abs(negativ(nv-1)) + Math.abs(negativ(nv-2)));
}
}
The assumption I have made, above, is that the initial input to the function will always be positive. Your original code confirms this assumption.
-1 * (Math.abs(negativ(nv-1) + negativ(nv-2)));
Thus the result will be negative regardless of the values given.
Related
I am only interested in n < 0 case, if n == -3 then I get, 0.001 as desired.
but I reached here through trial and error. Can someone explain to me 'WHY' this works (for n < 0 case only)?
public static double power10(int n) {
if(n == 0){
return 1;
}
else if (n > 10){
return 10 * power10(n - 1);
}
else {
return 1.0 / power10(-n);
}
}
The Following Function works for both negative and positive powers.
double Power(int n1,int n2) {
if(n2>=0) {
if(n2==1) {
return n1;
}
if(n2==0) {
return 1;
}
else {
return n1*Power(n1,n2-1);
}
}
else {
if(n2==-1) {
return 1.0/n1;
}
else {
return 1.0/(n1*Power(n1,(-1)*(n2+1)));
}
}
It will create following recursion tree for Negative example,
This link will redirect you to the recursion tree to better understanding, How this function will work recursively.
In fact, your code doesn't work for either 3 or -3. A stack overflow occurs in both cases. I don't know how you got 0.003.
The error in your code is this:
else if (n > 10){
It should be n > 0. instead.
This recursive algorithm should be quite clear if we turn it into a sentence starting with "the nth power of 10 is...":
The nth power of 10 is:
If n is 0, 1
If n is positive, 10 * (n-1)th power of 10
If n is negative, 1 / -nth power of 10
You can see that all values of n are covered, whether it be 0, positive or negative. In your incorrect code, you treat cases where 0 < n < 10 as "negative numbers". When you negate those and recurse, you get a real negative number, it goes into the else again and they are negated again. But they are still not larger than 10, causing infinite recursion.
Your code here probably give out stack overflow error.
Try
else if(n>0)
Now under the above condition function return n th value of 10 and return 1000 (when n is 3 case), Giving you the answer 0.001.
I'm having trouble with this problem. I am supposed to find the amount of even digits in a number.
So for example, if the number is 146, then there are 2 even digits.
And if the number is 802, then there are 3 even digits.
I was told that n % 10 is the value of the rightmost digit. n / 10 contains all of the digits except the rightmost digit.
public static int countEvenDigits(int n) {
int rightDigit = n % 10;
int count= 0;
if (rightDigit / 10 == 0) {
count++;
}
return countEvenDigits(count);
}
With recursion, you can do it like this
int calcRec(int num) {
if (num / 10 == 0) {
return num % 2 == 0 ? 1 : 0;
}else{
return (num % 10 % 2 == 0? 1:0)+calcRec(num/10);
}
}
But its not suitable case for using recursion.
Another answer:
public static int countEvenDigits(int number) {
if (number == 0) return 0;
int lastDigit = number % 10;
int firstDigits = number / 10;
if (lastDigit % 2 == 0) {
return 1 + countEvenDigits(firstDigits);
} else {
return 0 + countEvenDigits(firstDigits);
}
}
Recursion always needs one or more "base case"s, where recursion stops (in this case, no digits left); and one or more "recursive cases" where you continue to work with a smaller problem (with the firstDigits).
I agree with #kimreik that this is not a good use of recursion (as the problem could be better solved with a while-loop); but it is a very typical example when starting to learn to program recursion, as I suspect the OP is doing.
Ok so the idea of using recursion to process a series is that you define a function that process and removes one element from the set. Seeing as you are interested in digits you have 2 options to define your set from a given int.
The first option is to cast the int to a string and cast each character back into an int. Which is what I implemented below
Alternatively you could do division by your base (10) to the power of the significance of the digit (0 being the right most digit and counting left.) Or more eloquently as kimreik reducing the number by integer division sequentially. (142 / 10 / 10 == 142 / 100 == 1 == "142"[0])...
The syntax for converting your integer to a string is Integer.toString(int). This will be useful as it allows us to access each digit without doing any math and also allows us to take sub-strings which we can pass to the next instance of our recursive method.
Now that we have our array to process we need to address the fundamentals of recursion. Recursion has three parts. These parts are as follows, some starting state or initial values, a base case and a recursive step.
For this problem we must set our initial values for the count of even digits and we will be given a string to process. We will start our count at 0 but it will be a variable passed to each call to our method.
Our base case is the empty sting, that is a blank number. Which contains 0 even numbers. Because we are recurring towards an empty set this type of algorithm is called reductive.
Now our recursive step is where everything really happens. It must read a digit from our string and then remove it from the string by passing the remaining digits to the next instance of the function.
Now that we know what we need to do what does out function look like?
public class HelloWorld{
public static int recursiveGetEvenDigits(String arg){
int count = 0;
if(arg.length()<1){
return(0); // base case
}
else{
count = Character.getNumericValue(arg.charAt(0))%2 == 0 ? 1 : 0; //If else shorthand
return(count+recursiveGetEvenDigits(arg.substring(1)));
}
}
public static int getEvenDigits(int n){ // provide user arguments
return(recursiveGetEvenDigits(Integer.toString(n))); // set initial conditions
}
public static void main(String []args){
System.out.println(getEvenDigits(142));
}
}
Just to be funny the whole if else logic could be reduced to one line again with the same shorthand I used above.
public class HelloWorld{
public static int recursiveGetEvenDigits(String arg){
return arg.length() < 1 ? 0 : (Character.getNumericValue(arg.charAt(0)) % 2 == 0 ? 1 : 0)+recursiveGetEvenDigits(arg.substring(1));
}
public static int getEvenDigits(int n){ // provide user arguments
return(recursiveGetEvenDigits(Integer.toString(n))); // set initial conditions
}
public static void main(String []args){
System.out.println(getEvenDigits(142));
}
}
prints 2
here is a quick pseudo code
function sumEven(int num){
if(num==0)
return 0;
int var =num%10;
if(var % 2)
return var+(num/10)
else
return 0+(num/10)
}
I am trying to understand why the below functions are outputting zero for any input I give them. I would have thought that based on the recursive nature that inputting a 2 to function g, would produce 12. Any integer I seem to use for either function simply outputs 0. Can anyone point to where I am going wrong in my thought process?
public class dsdsfsd {
public static int i(int n) {
if (n == 0) return 0;
return i(n-1) + g(n-1);
}
public static int g(int n) {
if (n == 0) return 0;
return g(n-1) + i(n);
}
public static void main(String[] args) {
int a = 2;
System.out.println(g(a));
System.out.println(i(a));
System.out.println(g(g(a)));
}
}
Sure. The only value these functions can return is 0. That's the base case, and the higher cases do nothing but add up those zeroes. Where do you see another value entering the equation?
If either function has zero as an argument, it returns 0.
If it has any other value, it returns the sum of two recursive calls.
The sum of two zeros is zero.
Where exactly do you expect the function to produce anything but zero?
Your problem is not on the recurrence but on the initialization of your variables.
I reckon that you try to calculate some linked coefficients by the formulas:
g(n) = g(n-1) + i(n)
i(n) = i(n-1) + g(n-1)
g(0) = 0
i(0) = 0
However, as you initialized g and i to 0, i(1) = g(0) + i(0) = 0 + 0 = 0, and any values of g(n) or i(n) will be 0 for the same reason which is: you keep adding 0's and 0's.
Instead if you want to have a non-null result you should change at least one of your initialization, for example:
g(0) = 1
i(0) = 1
That way, you have i(1) = g(0) + i(0) = 1 + 1 = 2 and g(1) = g(0) + i(1) = 1 + 2 = 3.
This is more a mathematical issue in the end.
You could reduce this to a single function for simplicity, since the mutual recursion is irrelevant:
public static int func(int n) {
if (n == 0) return 0;
return func(n-1);
}
Notice there are only 2 ways for this to return:
It can return 0 directly in the base case
It can return the result of recursing.
Think about that. At some point, it must stop recursing (or else it will run forever). What happens when the base case of 0 is returned? Your function turns into something like this (for imagining purposes only of course):
public static int func(int n) {
if (n == 0) return 0;
return 0;
}
Therefore, 0 is the only value your function(s) are capable of returning, since it's the only concrete value ever returned.
Problem: check if a number is a power of 4.
my solution in java:
public static boolean isPowerOfFour(int num) {
return (Math.log(num) % Math.log(4) == 0);
}
But it seems off in some cases, for example when num is 64.
I found out that if I change the code a little bit, it works well.
public static boolean isPowerOfFour(int num) {
return (Math.log(num) / Math.log(4) %1 == 0);
}
I think both solutions do the same thing, check if the remaining of logNum/logBase is 0. But why the first solution doesn't work? Is it because the solution is incorrect or relative to some low level JVM stuff?
Thanks.
Building on #dasblinkenlight's answer, you can easily combine both conditions (first, a power of 2, then any power of 4 among all possible powers of 2) with a simple mask:
public static boolean isPowerOfFour(int num) {
return ((( num & ( num - 1 )) == 0 ) // check whether num is a power of 2
&& (( num & 0xaaaaaaaa ) == 0 )); // make sure it's an even power of 2
}
No loop, no conversion to float.
Checking if a number is a power of 4 is the same as checking that the number is an even power of 2.
You can check that a number x is a power of two by verifying that x & (x-1) is zero (here is the explanation of how this works)
If your number is not a power of 2, return false. Otherwise, shift the number right until you get to one, and count the number of shifts. If you shifted an odd number of times, return false; otherwise, return true:
public static boolean isPowerOfFour(int num) {
if ((num & (num-1)) != 0) {
return false;
}
int count = 0;
while (num != 1) {
num >>= 1;
count++;
}
return count % 2 == 0;
}
Demo.
Functions like Math.log return floating point numbers with a rounding error. So when num = 64 for example, Math.log (num) / Math.log (4) is not exactly 3, but a number close to 3.
public static boolean isPowerOfFour(int num) {
if (num > 0) {
while (num % 4 == 0) num /= 4;
}
return (num == 1);
}
This solution can be quite easily adapted to check whether num is a power of some other integer greater than 1.
The reason it doesn't work is because Math.log() returns a double. The answer of false is reflective of rounding errors; log(64) base e is an irrational number but Java needs to truncate it to fit it's width.
This question already has answers here:
How to round up the result of integer division?
(18 answers)
Closed 4 years ago.
I just wrote a tiny method to count the number of pages for cell phone SMS. I didn't have the option to round up using Math.ceil, and honestly it seems to be very ugly.
Here is my code:
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String message = "today we stumbled upon a huge performance leak while optimizing a raycasting algorithm. Much to our surprise, the Math.floor() method took almost half of the calculation time: 3 floor operations took the same amount of time as one trilinear interpolation. Since we could not belive that the floor-method could produce such a enourmous overhead, we wrote a small test program that reproduce";
System.out.printf("COunt is %d ",(int)messagePageCount(message));
}
public static double messagePageCount(String message){
if(message.trim().isEmpty() || message.trim().length() == 0){
return 0;
} else{
if(message.length() <= 160){
return 1;
} else {
return Math.ceil((double)message.length()/153);
}
}
}
I don't really like this piece of code and I'm looking for a more elegant way of doing this. With this, I'm expecting 3 and not 3.0000000. Any ideas?
Use Math.ceil() and cast the result to int:
This is still faster than to avoid doubles by using abs().
The result is correct when working with negatives, because -0.999 will be rounded UP to 0
Example:
(int) Math.ceil((double)divident / divisor);
To round up an integer division you can use
import static java.lang.Math.abs;
public static long roundUp(long num, long divisor) {
int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);
return sign * (abs(num) + abs(divisor) - 1) / abs(divisor);
}
or if both numbers are positive
public static long roundUp(long num, long divisor) {
return (num + divisor - 1) / divisor;
}
Another one-liner that is not too complicated:
private int countNumberOfPages(int numberOfObjects, int pageSize) {
return numberOfObjects / pageSize + (numberOfObjects % pageSize == 0 ? 0 : 1);
}
Could use long instead of int; just change the parameter types and return type.
Google's Guava library handles this in the IntMath class:
IntMath.divide(numerator, divisor, RoundingMode.CEILING);
Unlike many answers here, it handles negative numbers. It also throws an appropriate exception when attempting to divide by zero.
(message.length() + 152) / 153
This will give a "rounded up" integer.
long numberOfPages = new BigDecimal(resultsSize).divide(new BigDecimal(pageSize), RoundingMode.UP).longValue();
If you want to calculate a divided by b rounded up you can use (a+(-a%b))/b
Expanding on Peter's solution, this is what I've found works for me to always round 'towards positive infinity':
public static long divideAndRoundUp(long num, long divisor) {
if (num == 0 || divisor == 0) { return 0; }
int sign = (num > 0 ? 1 : -1) * (divisor > 0 ? 1 : -1);
if (sign > 0) {
return (num + divisor - 1) / divisor;
}
else {
return (num / divisor);
}
}
this might be helpfull,,
Subtract the remainder to the legnth and make it a divisible number and then divide it with 153
int r=message.length()%153; //Calculate the remainder by %153
return (message.length()-r)/153; // find the pages by adding the remainder and
//then divide by 153