Implementing my own pow function in Java - java

This is a popular interview question. Implementing my own pow function.
There are some popular recursive approaches available online but I'm trying to do it iteratively. The code works for n > 0, but I'm a little lost when it gets below 0. Here's my code.
public double myPow(double x, int n) {
if(x == 0) return 0;
if(n == 0) return 1;
double result = 1;
if(n > 0 ){
for(int i=1; i <= n; i++){
result = result * x;
}
}else{
for(int i=1; i<= n; i++){
//calculate the nth root
}
}
return result;
}
Any help appreciated with calculating the nth root.

I guess you can do that: (because x^(-n) = 1/x^n)
double positive_pow(double x, int n) {
if(x == 0) return 0;
if(n == 0) return 1;
double result = 1;
if(n > 0 ){
for(int i=1; i <= n; i++){
result = result * x;
}
}else{
for(int i=1; i<= n; i++){
//calculate the nth root
}
}
return result;
}
public double pow(double x, int n) {
if (n > 0) return positive_pow(x, n);
else if (n == 0) return 1;
else return 1 / positive_pow(x, 0-n);
}
This is not the shortest way to implement this, but it is based on your base function and it's more clear than recursively calculating it or messing around with Math functions.

This will work.
This code will be returning result for negative powers as well. For the explanation I have used the variable int p= x for my calculation of negative powers.....
public static double Pow(int x,int n){
if(x == 0) return 0;
if(n == 0) return 1;
double result = 1;
if(n > 0 ){
for(int i=1; i <= n; i++){
result = result * x;
}
}
else{
int p=x;
for(int i=0; i>n; i--){
if(result==1){
result= 1/(result*x);
result++;
}
else{
p=p*x;
result= (1.0)*1/p;
}
}
}
return result;
}

Try this, I wrote this one when I was practicing Java. The idea is 5^62=5^(32+16+8+4+2)=5^32*5^16*5^8*5^4*5^2, and in binary code, 62 is 00111110.
Here is the code:
double pow(double x, int n){
int i;
double result;
result = 1;
i = x;
while(n != 0){
if(n & 1 == 1){
result *= i;
}
i *= i;
n>>1;
}
return result;
}

Related

Java Comparison of If/While Loop

Working on a leetcode problem described as: "Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's."
I am using a sliding window approach and had produced the below code:
class Solution {
public int longestOnes(int[] nums, int k) {
int current = 0;
int left = 0;
int ans = 0;
for (int right = 0; right < nums.length; right++){
if (nums[right] == 0){
current++;
}
while (current > k){
if (nums[left] == 0){
current--;
}
left++;
}
ans = right - left + 1;
}
return ans;
}
}
This produces a logical error in the ouptut where the value returned is off by 1 in either direction depending on the test. I replaced the while loop with in if statement shown in the code below which fixed the error. Why is this the case?
class Solution {
public int longestOnes(int[] nums, int k) {
int current = 0;
int left = 0;
int ans = 0;
for (int right = 0; right < nums.length; right++){
if (nums[right] == 0){
current++;
}
if (current > k){
if (nums[left] == 0){
current--;
}
left++;
}
ans = right - left + 1;
}
return ans;
}
}
I expected the while loop to run once and be equivalent as the block should evaluate the condition on each iteration and then act if the condition is true. What is happening here?
Solution moved from #SiggyWeb's question post:
Solution found via feedback from the comments
class Solution {
public int longestOnes(int[] nums, int k) {
int current = 0;
int left = 0;
int ans = 0;
for (int right = 0; right < nums.length; right++){
if (nums[right] == 0){
current++;
}
while (current > k){
if (nums[left] == 0){
current--;
}
left++;
}
ans = Math.max(ans,right - left + 1);
}
return ans;
}
}

Writing a Power method with a minimum amount of steps n(log)N

I'm trying to write the Power method and now the question is how to write it in a better way. Here is my code, I've verified it works well for all the Power conditions, however I can't think on a better solution.
The real issue is how I express the power with a Negative exponent in O(log)n condition
public static double raiseToPowerIterative(double x, int n) {
double sol = 1;
if (n == 0) {
return 1;
}
if (n > 0) {
for (int i = 1; i <= n;i++) {
sol *= x;
}
return sol;
} else if (n < 0){
for (int i = -1; i >= n; i--) {
sol /= x;
}
}
return sol;
}
You need some additional math rules, you are using:
xn = x.x. ... .x (n times)
With O(n)
However
x2k = xk . xk
x2k+1 = x.x2k
Which can deliver O(²log n), as you are doing exponents n → n/2 → n/2/2 → ... → 1.
Where you only need to calculate xk once.
A recursive solution might be easiest; calling oneself for xk.
Your solution:
That does not work, I think. As probably past limit date of the work.
Wrong:
double power(double x, int n) {
if (n == 0) {
return 1;
}
boolean negative = ( n < 0 );
if (negative) {
n = -n;
}
double sol = 1;
while (n > 0) {
if (n%2 == 1) {
sol *= x;
}
x *= x;
n /= 2;
}
if (negative) {
return 1 / sol;
}
return sol;
}
Correct recursive:
double power(double x, int n) {
if (n == 0) {
return 1;
} else if (n < 0) {
return 1 / power(x, -n);
}
double sqrPower = power(x, n/2);
int p = sqrPower * sqrPower;
if (n % 1 == 1) {
p *= x;
}
return p;
}
That is, one has to do something with the result of the recursive call.
For an iterative loop one would need a stack to reconstruct the result.
Correct iterative:
double power(double x, int n) {
if (n == 0) {
return 1;
}
boolean invert = n < 0;
if (invert) {
n = -n;
}
Stack<Double> factors = new Stack<>();
while (n > 0) {
factors.push(n % 1 == 1 ? x : 1.0);
n /= 2;
}
double sol = 1;
while (!factors.empty()) {
double f = factors.pop();
sol = sol * sol * f;
}
return invert ? 1/sol : sol;
}

What is wrong with my java code for Project Euler's program 4? (finding the largest palindrome of 2 3 digit numbers)

This is my code and the answer always seems to 100001 (its not even
performing the loop).
I know there are much easier ways to solve this problem but what exactly is wrong with this particular code? and how do I fix it?
public class LargestPalindromes
{
public static void main(String[] args)
{
int largest = 100001;
for(int i = 100; i < 1000; i++)
{
for(int j = 100; j < 1000; j++)
{
int mult = i * j;
if(largest < mult && isPalindrome(mult))
largest = mult;
}
}
System.out.printf("\n\nThe largest palindrome is: %d\n\n", largest);
}
public static boolean isPalindrome(int mult)
{
int n1=0, n2=0, n3=0, n4=0, n5=0, n6=0;
int largest = 0, count = 0, p =100000;
int x = mult;
while(count < 6)
{
if(count == 1)
n1 = x / p;
else if(count == 2)
n2 = x / p;
else if(count == 3)
n3 = x / p;
else if(count == 4)
n4 = x / p;
else if(count == 5)
n5 = x / p;
else if(count == 6)
n6 = x / p;
x %= p;
p /= 10;
count++;
}
int reverse = Integer.valueOf(String.valueOf(n1) + String.valueOf(n2) + String.valueOf(n3) + String.valueOf(n4) + String.valueOf(n5) + String.valueOf(n6));
return reverse == mult;
}
}
There were too many errors in your original public static boolean isPalindrome(int mult) method. So I replaced it with the standard version:
public static boolean isPalindrome(int mult)
{
int temp=mult;
int r,sum=0;
while(mult>0){
r=mult%10; //getting remainder
sum=(sum*10)+r;
mult=mult/10;
}
if(temp==sum)
return true;
else{
return false;
}
}

Even Factorial Method in Java. I have tried everything and can't figure it out

Ok in this method I am supposed to compute the factorial using only the evens. So for example if I inputed 7 for n I would expect 6*4*2 = 48. I am supposed to fix the code so it will work. I have tried for like an hour now and don't know what I am doing wrong. Here is my code:
int p07EvenFactorial(int n) {
if (n % 2 == 1) {
n--;
}
int fact = 1;
for (int i = n; i > 0; i--) {
fact = fact + 2 * i;
}
return fact;
}
how about
int p07EvenFactorial(int n) {
if (n % 2 == 1) {
n--;
}
int fact = 1;
for (int i = 2; i <= n; i = i + 2) {
fact = fact * i;
}
return fact;
}
How about this
public int fact(int n) {
if(n % 2 ==1){
n = n -1;
}
if(n == 0){
return 1;
} else {
return n*fact(n-2);
}
}

More efficient way of calculating prime factorisation?

I currently have a program to find the prime factorisation of a given number; works fine with smaller numbers, but it takes ages for anything over a million. My code is extremely inefficient, finding all prime numbers below the input and checking which ones divide without a remainder. I don't know how to make it less inefficient, any help?
static ArrayList<Integer> primeNumbersBelow(long n) {
ArrayList<Integer> ay = new ArrayList<Integer>();
ay.add(2);
for(int i = 3; i < ((n % 2 != 0) ? (n + 1) / 2 : n / 2); i++) {
boolean divides = false;
for(int j = 2; j < i; j++) {
if(i % j == 0) {
divides = true;
}
}
if(!divides) {
ay.add(i);
System.out.println(i);
}
}
return ay;
}
static ArrayList<Integer> primeFactorisationOf() {
ArrayList<Integer> ay = new ArrayList<Integer>();
ArrayList<Integer> aay = primeNumbersBelow(input);
long n = input;
for(int i = 0, len = aay.size(); i < len; i++) {
int f = aay.get(i);
boolean run = true;
while(run) {
if(n % f == 0) {
ay.add(f);
n /= f;
} else {
run = false;
}
}
}
return ay;
}
From Mr Lars Vogel # vogella...
public static List<Integer> primeFactors(int number) {
int n = number;
List<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
return factors;
}
Sticking to your general algorithm and not re-writing your primesBelow(..) method: I would say:
Once divides = true, you can break out of the for-loop
The complex for loop termination condition for primality check can be reduced to the Math.sqrt(n) - I won't go through the math, but you can look that up yourself.
One way to improve the code is to remove the IO inside your loop structure.
That is,
static ArrayList<Integer> primeNumbersBelow(long n) {
ArrayList<Integer> ay = new ArrayList<Integer>();
ay.add(2);
for(int i = 3; i < ((n % 2 != 0) ? (n + 1) / 2 : n / 2); i++) {
boolean divides = false;
for(int j = 2; j < i; j++) {
if(i % j == 0) {
divides = true;
}
}
if(!divides) {
ay.add(i);
//REMOVE THE FOLLOWING LINE
System.out.println(i);
}
}
return ay;
}
I'm sure you'll see a huge performance boost just from that alone.

Categories

Resources