i'm creating recursion method that calculate Log base 2. for log*(1) = should be 0. log*(4) = should be 2. but my method only print out zero and i couldn't figure out the problem.can some one help me?
public static int logCalculator(double n) {
if (n == 1) {
return 0;
} else {
return 1 + logCalculator(n * n);
}
}
This will work for base 2 logs
public static int logCalculator1(double n) {
if (n < 2)
return 0;
return 1 + logCalculator1(n / 2);
}
NOTE: this will round down always and with high numbers is inaccurate, in addition you can make it for all bases like this:
public static int logCalculator(int base, double n) {
if (base > 0) {
if (n < base) {
return 0;
} else {
return 1 + logCalculator(base, (int)(n / base));
}
} return 0;
}
Related
I'm trying to calculate the time complexity of this code that sums the odd numbers of an array. I have done two methods and now I need to calculate the order complexity O(n)
This one is done by weak post-condition.
private static int sumaImparDebilit(int t[], int desde, int hasta) {
if (desde==hasta) {
if ((t[desde] % 2) == 1) {
return t[desde];
}
return 0;
}
if (t[desde]%2 == 1) {
return (t[desde] + sumaImparDebilit(t,(desde+1),hasta));
}
return (sumaImparDebilit(t,(desde+1),hasta));
}
This one is done by strong pre-condition.
private static int sumaImparFortalec(int t[], int hasta, int limite, int parcial) {
if (hasta <= limite) {
if ((t[hasta] % 2) == 1) {
return sumaImparFortalec(t,(hasta + 1),limite,(parcial + t[hasta]));
} else {
return sumaImparFortalec(t,(hasta + 1),limite,(parcial));
}
}
else {
return parcial;
}
}
I don’t know what you mean by “weak” and “strong” conditions, but both have time complexity O(n) and employ (for no good reason) recursion.
Surely this is simplest, and fastest:
int sum = 0;
for (int i = 0; i < t.length; i++)
if (t[i] % 2 == 1)
sum += t[i];
I'd like to change this exponentiation method (n is the exponent):
public static double exponentiate(double x, int n) {
counter++;
if (n == 0) {
return 1.0;
} else if (n == 1) {
return x;
} else {
return x * exponentiate(x, n - 1);
}
}
I'd like to change the method to make it more efficient, so the method is not opened n times but maximum (n/2+1) times WITHOUT using the class MATH.
So far I came up with this code:
public static double exponentiate(double x, int n) {
counter++;
if (n == 0) {
return 1.0;
} else if (n == 1) {
return x;
} else {
if (n % 2 == 0) {
n = n-(n-1);
} else {
n = ((n-1) / 2) + n;
}
return ((x * x) * exponentiate(x, n - (n / 2)));
}
}
But somehow it only works for odd n, not vor even n.
Can somebody help?
Thanks!
I think you can optimize the above method to run for O(logn) by calculating exponentiate(x,n/2) once and using it.
Something like this:-
public static double exponentiate(double x, int n)
{
int temp;
if(n == 0)
return 1;
temp = exponentiate(x, n/2);
if (n%2 == 0)
return temp*temp;
else
return x*temp*temp;
}
Hope this helps!
I don't know if this is the solution you search but this is an example of an algorithm that perform exponentiation in O(log(n)) time
public static double exponentiate(double x, int n) {
if (n == 0) {
return 1.0;
} else if (n == 1) {
return x;
} else {
return ((n % 2 == 0) ? 1 : x) * exponentiate(x * x, n / 2);
}
}
Need to write a method that returns the number of digits foe an integer number.
At first I did it using the iterative approach and everything worked just fine, however, when I want to edit the code using recursion I'm always stuck at the first counting and can't figure out why.
Any help is much appreciated..
public static int numberLength(int n) {
if (n < 0) {
n *= (-1);
} else if (n == 0) {
return 1;
}
int digits = 0;
if (n > 0) {
digits += 1;
numberLength(n / 10);
}
return digits;
In a recursive method you need to return some value based on reducing the size of the input value and combining this with your current count so far e.g.
public static int numberLength(int n){
if(n < 10){
return 1;
}
return 1 + (numberLength(n/10)); //This line combines the result
}
The problem is that you're discarding the result of numberLength(n / 10);
You probably meant to type:
int digits = 0;
if (n > 0) {
return 1 + numberLength(n / 10);
}
return digits;
A possible solution could look like this:
public static int numberLength(int n){
if(n < 0){
return numberLength(-n);
}
else if(n == 0){
return 0;
}
else{
return 1 + numberLength(n/10);
}
}
public static void main(String[] args){
System.out.println(numberLength(-152555)); //returns 6
}
I have implemented a recursive function to find m^n (m raised to the power n).
Now I want to implement the same function but by dividing the problem into two equal parts, like
m^n = m^(n/2) * m^(n/2) = ... (for even n like, m^2, m^4, m^6).
With the implementation below, if I give m = 2 and n = 4, my output is 4 while it should be 16.
public class Recursion {
public static void main(String[] args) {
System.out.println(pow(2, 4));
}
public static long pow(long m,long n) {
if (n > 0)
return m * pow(m, ((n/2) - 1) * pow(m, ((n/2) - 1)));
else
return 1;
}
}
public static long pow(long m,long n)
{
if (n <= 0) {
return 1; // Be lazy first
} else if (n % 2 == 1) {
return m * pow(m, n - 1); // Normal slow strategy
} else { // n even
long root = pow(m, n / 2); // Do not evaluate twice
return root * root;
}
}
Based on a combination of two other answers here, I believe this is the optimal algorithm:
public static long pow(long m, int n)
{
if (n <= 0) {
return 1;
} else if (n == 1) {
return m;
}
int rem = n & 1;
n >>= 1;
if (rem == 0) {
return pow(m * m, n); // x^(2n) = (x^2)^n
} else {
return m * pow(m * m, n); // x^(2n+1) = x * ((x^2)^n)
}
}
i.e. an immediate short-circuit for m^0 or m^1, and a single recursive call for other cases.
EDIT cleaned up slightly and now exactly follows the Wikipedia article on exponentiation by squaring which was algorithmically the same as my previous edit but is now improved by being the even-case being potentially tail recursive on languages that support it.
Try this, it computes by splitting into two parts as required. Also look at http://en.wikipedia.org/wiki/Exponentiation_by_squaring for other methods
class Main {
public static void main(String[] args) {
System.out.println(pow(2, 4));
}
public static long pow(long m, long n) {
if (n > 1)
return pow(m, (n / 2)) * pow(m, (n - (n / 2)));
else if (n <= 0)
return 1;
else
return m;
}
}
This answer adds error reporting on invalid inputs and handles all corner cases:
public long pow(long base, long exponent) {
if (exponent < 0) {
if (base == 1) {
return 1;
} else if (base == -1) {
return exponent % 2 == 0 ? 1 : -1;
} else {
throw new ArithmeticException("Negative exponent");
}
} else if (exponent == 0) {
if (base == 0) {
throw new ArithmeticException("0**0 is undefined");
} else {
return 1;
}
} else {
long root = pow(base, exponent/2);
long result = root * root;
if (exponent % 2 != 0) {
result *= base;
}
return result;
}
}
Technically this computes the result truncated to fit in a long. To detect overflow, the multiplications should be replaced with something like this.
For a non-recursive solution, replace the final else-block with
long result = 1;
while (exponent != 0) {
if (exponent % 2 != 0) {
result *= base;
}
base *= base;
exponent /= 2;
}
return result;
if you add up you ms you have
1+n/2-1+n/2-1
which reduces to
n - 1
Also, you have misplaced a few parenthesis, so you are not actually multiplying where you think you are. You are multiply the result of pow((n/2) -1) to the partialnin your firstpow` call.
A prime heavy number is defined to be one that is the sum of more than one pair of prime numbers. Recall that a prime number is a number greater than 1 whose only divisors are 1 and itself.
For example, 16 is prime heavy because 16=3+13 and 5+11 (note that 3, 5, 11, and 13 are all prime). 24 is prime heavy because 24 = 5+19, 7+17 and 11+13. However, 8 is not prime heavy because 8 = 3+5 but no other pair of primes sums to 8.
Write a function named isPrimeHeavy that returns 1 if its argument is prime heavy, otherwise it returns 0.
The function signature is
int isPrimeHeavy (int n)
You may assume that a function named isPrime already exists that returns 1 if its argument is a prime. You can call this function but do not have to write it.
I did this but it cant return a heavy prime..just returns a prime number...
public class Prime {
public static boolean isPrimeHeavy(int n) {
if (n <= 1) {
return false;
}
if (n == 2) {
return true;
}
for (int i = 2; i <= Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static boolean isPrimeHeavy(int n) {
if (n <= 1) {
return false;
}
if (n == 2) {
return true;
}
if (n % 2 == 0) {
return false;
}
for (int i = 3; i <= Math.sqrt(n) + 1; i = i + 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
public class PrimeTest {
public PrimeTest() {
}
#Test
public void testIsPrime() throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
Prime prime = new Prime();
TreeMap<Long, String> methodMap = new TreeMap<Long, String>();
for (Method method : Prime.class.getDeclaredMethods()) {
long startTime = System.currentTimeMillis();
int primeCount = 0;
for (int i = 0; i < 1000000; i++) {
if ((Boolean) method.invoke(prime, i)) {
primeCount++;
}
}
long endTime = System.currentTimeMillis();
Assert.assertEquals(method.getName() + " failed ", 78498, primeCount);
methodMap.put(endTime - startTime, method.getName());
}
for (Entry<Long, String> entry : methodMap.entrySet()) {
System.out.println(entry.getValue() + " " + entry.getKey() + " Milli seconds ");
}
}
}
You can use a single loop to try all the possible first values and you can calculate the second, when you find there is more than one pair, return 1, otherwise return 0.
I have given you this much as a hint because its maths really rather than programming. You will find problems like this at Project Euler. IMHO You shouldn't be expected to know how to solve the maths problem unless you are employed for a maths role, but you should be able to write the code if you are a professional developer.
if((argument % 2 == 0 && argument > 12) || argument == 10) {
return 1;
} else {
return 0;
}
public class Prime {
public static boolean isPrimeHeavy(int n) {
if (n % 2 != 0) {
return false;
}
int found = 0;
for (int i = n-3; i >= (n/2); i -= 2) {
if (isPrime(i) && isPrime(n - i)) {
found++;
if (found == 2)
return true;
}
}
return false;
}
}