Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I must calculate X to the power of Y with recursion and only addition. I really can't figure out how to do it without using loops or using multiplication. This is not my homework. It is a question from last years exams I am stuck on.
import java.util.Scanner;
public class Season4Task7 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter X");
int x = sc.nextInt();
System.out.println("Enter y");
int y = sc.nextInt();
System.out.println(findXY(x, y, 0));
}
static int findXY(int x, int y, int result){
if(y==0){
return 1;
}
if(x==0){
return 0;
}
if(y==1){
return result+x;
}
result+=x;
return findXY(x, y-1, result);
}
}
First two ifs look fine, maybe the 'y-1' as well but after that it might be incorrect, also is there a chance not to use 'int result' but only to pass x and y to the function?
Since we cannot using multiplication, we need to use recursive addition. check my code below. Your first 3 if conditions are correct. Modify the later code to below method.
package com.java;
import java.util.Scanner;
public class Season4Task7 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter X");
int x = sc.nextInt();
System.out.println("Enter y");
int y = sc.nextInt();
System.out.println("Final :: " + findXPowerY(x, y));
sc.close();
}
static int findXPowerY(int x, int y) {
if (y == 0) {
return 1;
}
if (x == 0) {
return 0;
}
if (y == 1) {
return x;
}
return multiply(x, findXPowerY(x, y - 1));
}
static int multiply(int x, int y) {
if (y != 0)
return (x + multiply(x, y - 1));
else
return 0;
}
}
What your findXY method really does is simple multiplication, not exponentiation. First of all, it could be improved from using 3 parameters to only 2:
static int findXY(int x, int y){
if(y==0){
return 1;
}
if(x==0){
return 0;
}
if(y==1){
return x;
}
return x + findXY(x, y-1);
}
Secondly, you are halfway done! You just found a way to multiply with only using addition and recursion. What you now need to do, is call this multiplication certain numer of times, again, using recursion.
Before we start, let's rename the method from findXY to multiply, since it better indicates its intent and functionality.
Thirdly, we need to implement the method that calculates the power. Keeping in mind that we renamed your findXY method to multiply and changed the number of parameters from 3 to 2, our implementation might look like this:
static int power(int x, int y) {
if(y == 0) {
return 1;
}
if(y == 1) {
return x;
}
return x * power(x, y-1));
}
Hey, but we are not allowed to use multiplication! Fortunately, we made our own implementation! The final product looks like this:
static int power(int x, int y) {
if(y == 0) {
return 1;
}
if(y == 1) {
return x;
}
return multiply(x, power(x, y-1));
}
Please do note that this approach does not work with negative numbers. If they are the case, you could wrap this method in another one that simply calls power with abs value and inverts the result
today i heard about this website called codility where a user can give various programming test to check their code's performance.
When I started, they presented me with this sample test,
Task description A small frog wants to get to the other side of the
road. The frog is currently located at position X and wants to get to
a position greater than or equal to Y. The small frog always jumps a
fixed distance, D. Count the minimal number of jumps that the small
frog must perform to reach its target.
Write a function:
class Solution { public int solution(int X, int Y, int D); }
that, given three integers X, Y and D, returns the minimal number of jumps from position X to a position equal to or greater than Y.
For example,
given:
X = 10
Y = 85
D = 30 the function should return 3,
because the frog will be positioned as follows:
after the first jump,
at position 10 + 30 = 40
after the second jump, at position 10 + 30 + 30 = 70
after the third jump, at position 10 + 30 + 30 + 30 = 100
Assume that: X, Y and D are integers within the range
[1..1,000,000,000]; X ≤ Y. Complexity: expected worst-case time
complexity is O(1); expected worst-case space complexity is O(1).
The question was pretty straight forward and it took me like 2 minutes to write the solution, which is following,
class Solution {
public int solution(int X, int Y, int D) {
int p = 0;
while (X < Y){
p++;
X = X + D;
}
return p;
}
}
However, the test result shows that the performance of my code is just 20% and I scored just 55%,
Here is the link to result, https://codility.com/demo/results/demo66WP2H-K25/
That was so simple code, where I have just used a single while loop, how could it possibly be make much faster ?
Basic math:
X + nD >= Y
nD >= Y - X
n >= (Y - X) / D
The minimum value for n will be the result of rounding up the division of (Y - X) by D.
Big O analysis for this operation:
Complexity: O(1). It's a difference, a division and a round up
Worst-case space complexity is O(1): you can have at most 3 more variables:
Difference for Y - X, let's assign this into Z.
Division between Z by D, let's assign this into E.
Rounding E up, let's assign this into R (from result).
Java(One Line), Correctness 100%, Performance 100%, Task score 100%
// you can also use imports, for example:
// import java.util.*;
// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int X, int Y, int D) {
return (int) Math.ceil((double) (Y - X) / (double) D);
}
}
Here is the 100% total score Python solution:
def solution(X, Y, D):
# write your code in Python 3.6
s = (Y-X)/D
return int(-(-s // 1))
class Solution {
public int solution(int x, int y, int d) {
return (y - x + d - 1) / d;
}
}
class Solution {
public int solution(int x, int y, int d) {
// write your code in Java SE 8
System.out.println("this is a debug message"+(y-x)%d);
if((y-x)%d == 0)
return ((y-x)/d);
else
return (((y-x)/d)+1);
}
}
C# got 100 out of 100 points
using System;
// you can also use other imports, for example:
// using System.Collections.Generic;
// you can write to stdout for debugging purposes, e.g.
// Console.WriteLine("this is a debug message");
class Solution {
public int solution(int X, int Y, int D) {
int Len= Y-X;
if (Len%D==0)
{
return Len/D;
}
else
{
return (Len/D)+1;
}
}
}
Here's Scala solution:
def solution(X: Int, Y: Int, D: Int): Int = {
//divide distance (Y-X) with fixed jump distance. If there is reminder then add 1 to result to
// cover that part with one jump
val jumps = (Y-X) / D + (if(((Y-X) % D) >0 ) 1 else 0)
jumps
}
Performance: https://codility.com/demo/results/trainingTQS547-ZQW/
Javascript solution, 100/100, and shorter than the existing answer:
function solution(Y, Y, D) {
return Math.ceil((Y - X) / D);
}
Here is a solution that brings the test performance to 100%
class Solution {
public int solution(int X, int Y, int D) {
if (X >= Y) return 0;
if (D == 0) return -1;
int minJump = 0;
if ((Y - X) % D == 0) {
minJump = (Y - X) / D;
} else minJump= (Y - X) / D +1;
return minJump;
}
}
JavaScript solution 100/100
function solution (x,y,d) {
if ((y-x) % d === 0) {
return (y-x)/d;
} else {
return Math.ceil((y-x)/d);
}
}
Using Java perfect code
100 score code in Java
public int solution(int X, int Y, int D) {
if(X<0 && Y<0)
return 0;
if(X==Y)
return 0;
if((Y-X)%D==0)
return (Y-X)/D;
else
return (((Y-X)/D)+1);
}
this is corrected code using java giving 91% pass
int solution(int A[]) {
int len = A.length;
if (len == 2) {
return Math.abs(A[1] - A[0]);
}
int[] sumArray = new int[A.length];
int sum = 0;
for (int j = 0; j < A.length; j++) {
sum = sum + A[j];
sumArray[j] = sum;
}
int min = Integer.MAX_VALUE;
for (int j = 0; j < sumArray.length; j++) {
int difference = Math.abs(sum - 2 * sumArray[j]);
// System.out.println(difference);
if (difference < min)
min = difference;
}
return min;
}
This is my solution with 100% (C#):
int result = 0;
if (y <= x || d == 0)
{
result = 0;
}
else
{
result = (y - x + d - 1) / d;
}
return result;
Here is my solution in PHP, 100% performance.
function solution($X, $Y, $D) {
return (int)ceil(($Y-$X)/$D); //ceils returns a float and so we cast (int)
}
Y-X gives you the actual distance object has to be travel ,if that distance is directly divsible by object jump(D) then ans will be (sum/D) if some decimal value is there then we have to add 1 more into it i.e(sum/D)+1
int sum=Y-X;
if(X!=Y && X<Y){
if(sum%D==0){
return (int )(sum/D);
}
else{
return ((int)(sum/D)+1);
}}
else{
return 0;
}
I like all the rest of the solutions, especially "(y - x + d - 1) / d". That was awesome. This is what I came up with.
public int solution(int X, int Y, int D) {
if (X == Y || X > Y || D == 0) {
return 0;
}
int total = (Y - X) / D;
int left = (Y - X) - (D * total);
if (left > 0) {
total++;
}
return total;
}
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(X, Y, D) {
let jumps = 0
//If 0 -> 100 with 2 step
// Answer would be 100/2 = 50
//If 10 -> 100 with 2 step
//Answer would be (100 - 10) / 2 = 45
jumps = Math.ceil((Y - X) / D)
return jumps
}
swift solution 100% PASS - O(1) complexity
import Foundation
import Glibc
public func solution(_ X : Int, _ Y : Int, _ D : Int) -> Int {
if X == Y {
return 0
}
var jumps = (Y-X)/D
if jumps * D + X < Y {
jumps += 1
}
return jumps
}
import math
def solution(X, Y, D):
if (X >= Y): return 0
if (D == 0): return -1
minJump = 0
#if ((Y - X) % D == 0):
minJump = math.ceil((Y - X) / D)
#else:
#minJump = math.ceil((Y - X) / D) +1
return minJump
This solution worked for me in Java 11:
public int solution(int X, int Y, int D) {
return X == Y ? 0 : (Y - X - 1) / D + 1;
}
Correctness 100%, Performance 100%, Task score 100%
#Test
void solution() {
assertThat(task1.solution(0, 0, 30)).isEqualTo(0);
assertThat(task1.solution(10, 10, 10)).isEqualTo(0);
assertThat(task1.solution(10, 10, 30)).isEqualTo(0);
assertThat(task1.solution(10, 30, 30)).isEqualTo(1);
assertThat(task1.solution(10, 40, 30)).isEqualTo(1);
assertThat(task1.solution(10, 45, 30)).isEqualTo(2);
assertThat(task1.solution(10, 70, 30)).isEqualTo(2);
assertThat(task1.solution(10, 75, 30)).isEqualTo(3);
assertThat(task1.solution(10, 80, 30)).isEqualTo(3);
assertThat(task1.solution(10, 85, 30)).isEqualTo(3);
assertThat(task1.solution(10, 100, 30)).isEqualTo(3);
assertThat(task1.solution(10, 101, 30)).isEqualTo(4);
assertThat(task1.solution(10, 105, 30)).isEqualTo(4);
assertThat(task1.solution(10, 110, 30)).isEqualTo(4);
}
Here is the JS implementation
function frogJumbs(x, y, d) {
if ((y - x) % d == 0) {
return Math.floor((y - x) / d);
}
return Math.floor((y - x) / d + 1);
}
console.log(frogJumbs(0, 150, 30));
100% C# solution:
public int solution(int X, int Y, int D)
{
var result = Math.Ceiling((double)(Y - X) / D);
return Convert.ToInt32(result);
}
It divides the total distance by length of a jump and rounds up the result. It came after multiple attempts and some web searches.
Here is the solution in Python giving a score of 100 on Codility:
import math
return math.ceil((Y-X)/D)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I found the The implements of Integer numberOfTrailingZeros method in java as follows
public static int numberOfTrailingZeros(int i) {
// HD, Figure 5-14
int y;
if (i == 0) return 32;
int n = 31;
y = i <<16; if (y != 0) { n = n -16; i = y; }
y = i << 8; if (y != 0) { n = n - 8; i = y; }
y = i << 4; if (y != 0) { n = n - 4; i = y; }
y = i << 2; if (y != 0) { n = n - 2; i = y; }
return n - ((i << 1) >>> 31);
}
It's take me a while to understand, here is my solution :
public static int numberOfTrailingZeros(int i) {
if (i == 0) return 32;
int num = 0;
while ((i & 1) == 0) {
i >>= 1;
num ++;
}
return num;
}
My question is what's the better solution? How can I come up with those implements such as in JDK Integer bitCount,highestOneBit,rotateLeft etc methods?
as I know the JDK's numberOfTrailingZeros use less + opeartor, and will be having higher performance when dealing with '0x70000000','0x60000000', and anything else?
What the java JDK is doing is sort of a binary search in the number to find the number of trailing zeros. It tries to shift the number left by powers of 2 to see if the shifted number becomes 0. If it doesn't, there are some set bits that are too far to the right, so the method keeps that shifted number, decrements the final count, and tries again with the next smallest power of 2.
Addition information:
Chip doesn't support multiplication, only addition. I should work around this problem by creating a recursive method, mult(), that performs multiplication
of x and y by adding x to itself y times. Its arguments are x and y and its return
value is the product of x and y. I should then write the method and a main() to
call it.
It's pure logical thinking, but I get lost every time I try to think what to do.
I am stuck at the math part..
What I have, that doesn't work and I know the math is wrong, but I am not good at this:
public static void mult(int x, int y) {
x = 0;
y = 0;
if (y > 0) {
for (int i = 0; i < y; i++) {
x = x * (x * y);
return mult(x, y);
}
}
}
When I hear "recursion", I expect to see two things:
A function calling itself with modified arguments each time.
A stopping condition right at the top that tells the function when to stop, avoiding an infinite stack.
So where are yours? Start with writing those down in words before you write code.
One possibility is to use an accumulator which will store the current value of the multiplication. I replace missing statements by ??? :
public static void main(String []args){
System.out.println(mult(2,5));
}
public static int mult(int x, int y) {
if(???) return ???;
else return multAcc(???,???,???);
}
private static int multAcc(int x, int y, int acc){
if(???) return ???;
else return multAcc(???, ???, ???);
}
... by adding x to itself y times.
You could actually do that, instead of multiplying. Oh, and maybe if you don't set both x and y to zero, you would have something to add ;-)
One last thing: If you want a recursive solution, you don't need the for-loop.
Java has no TCO by design, so using recursion for linear (not tree-like) processes is very bad idea. Especially for such task, which will most likely become a bottleneck in your program. Use loop instead.
Oh, it must be recursive anyway? Looks like a homework task. Do it yourself then.
All you need to remember is that a multiplication is a repeated addition (assuming that both operands are >= 0), so we have:
The base case is when y is zero
If y is not zero, then add x one more time, and subtract 1 from y
Notice that as long as y is positive, it'll eventually have a value of zero. So basically we keep adding x a total number of y times; this is what I mean:
public static int mult(int x, int y) {
if (y == 0)
return 0;
return x + mult(x, y-1);
}
The same code can be written in a tail-recursive style, too - meaning: there's nothing to do after the recursive call returns, and this is important for certain languages that support a so-called tail-call optimization:
public static int mult(int x, int y, int accumulator) {
if (y == 0)
return accumulator;
return mult(x, y-1, x + accumulator);
}
The above will get called as follows, noticing that the last parameter is always initialized in zero:
mult(10, 5, 0)
=> 50
public static int mult(int x, int y) {
if (y == 0) {
return 0;
}
if (y > 0) {
return x + mult(x, y - 1);
} else {
return -x + mult(x, y + 1);
}
}
this was the solution by the way
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
I faced an interview. where I was asked the following question
Write a function in any of programming language that computes the nth power of a number w/o using + * or ^ or declaring a new variable inside the function or using any library function (eg Math lib in java).
I have used pow function of java Math.pow(a, b)
Thanks
They're asking whether you understand recursion. Considering x ^ k for some integer k,
when k < 0, xk = xk+1 / x
when k = 0, xk = 1
when k > 0, xk = xk-1 * x
Turning this into code shouldn't be too bad. Let's use multiplication for now, and take it out later.
double recursivePower(double x, int k) {
if (k < 0) {
return power(x, ++k) / x;
} else if (k == 0) {
return 1;
} else {
return power(x, --k) * x;
}
}
Now, to get rid of the multiplication. Since n * m = n / (1/m), we can rewrite the last calculation as power(x, --k) / (1/x):
double recursivePower(double x, int k) {
if (k < 0) {
return recursivePower(x, ++k) / x;
} else if (k == 0) {
return 1;
} else {
return recursivePower(x, --k) / (1 / x);
}
}
Fractional exponents could probably be done in the same style. If they want irrational exponents to be handled in the same way, I'd ask for Google and a fair amount of time to think about the problem.
static public int power(int value, int pow){
if(pow == 0) return 1;
return value * power(value, pow -1);
}
Done in JavaScript:
function power(num,pow){
if (pow == 0) return 1
num /= 1/(power(num,--pow))
return num
}
Call it like:
power(2,0) // -> 1
power(5,2) // -> 25
power(7,3) // -> 343
I feel like inverse division is cheating the no * operator rule, but eh, maybe that's what they were looking for.
I am using java programming language. The interviewer restricted you to declare a new variable inside the method better you pass it to the function. The interviewer didnt restrict you to use division operator (/) so you can use that.
static double getNthPowerOfNumber(double originalNumber,
int power) {
if (power == 0) {
return 1;
}
if (originalNumber == 0) {
return 0;
} else {
originalNumber/=1/getNthPowerOfNumber(originalNumber, --power);
return originalNumber;
}
}
if you want to get 5th power of a number 3 then write System.out.println("4..double..." + getNthPowerOfNumber(4, 1));