I came across a class that solves an exponent problem but I couldn't wrap my head around how the method raiseToPower() works. This is the line that I don't understand: resultVal = baseVal * raiseToPower(baseVal,exponentVal-1);
What is baseVal being multiplied by? raiseToPower(baseVal,exponentVal-1) doesn't seem like an expression to me. If baseVal == 2, than what is raiseToPower(baseVal,exponentVal-1)?
I know how to solve 2^3 in my head, I struggle to understand the steps baseVal * raiseToPower(baseVal,exponentVal-1) takes to solve the problem. I know that exponentVal is decremented by 1 each time raiseToPower() is invoked, but I still don't understand how it's holding a value that can be multiplied by baseVal.
I understand that this recursive method behaves like a loop.
public class ExponentMethod {
// calculates the result of raising a number to a power
public static int raiseToPower(int baseVal, int exponentVal) {
int resultVal; // holds the answer to the exponent problem
// sets resultVal to 1
if (exponentVal == 0) {
resultVal = 1;
}
else {
// calculate math problem
resultVal = baseVal * raiseToPower(baseVal,exponentVal-1);
}
// returns when exponentVal == 0
return resultVal;
}
public static void main (String [] args) {
int userBase;
int userExponent;
userBase = 2;
userExponent = 3;
System.out.println(userBase + "^" + userExponent + " = "
+ raiseToPower(userBase, userExponent));
}
}
// output
2^3 = 8
I am aware that a pow() method exists for raising a number to a power
Thanks,
The method is using recursion to raise a specific base to a certain power.
Let us take a simple example of 2^2 and run through the code:
raiseToPower(2, 2) is called
resultVal = 2 * raiseToPower(2, 2 - 1) is run
raiseToPower(2, 1) is called
resultVal = 2 * raiseToPower(2, 1 - 1) is run
raiseToPower(2, 0) is called
Base case is hit and we return 1
Now we go back up the chain!
resultVal = 2 * 1 and 2 is returned
resultVal = 2 * 2 and 4 is returned
So the end result for 2^2 is 4 as expected.
Another way to think about this is suppose someone already gave you the answer to 2^2, can you use that to calculate 2^3? Yes, you can simply do 2 * 2^2!
So: raisePower(2,3) = 2 * raisePower(2,2)
It is important to also have a base case (when power is 0, like in your example above) so that we don't run into an infinite loop! Hope this helps.
What you are missing is that this is a recursive method which calls itself. It continues to do so, storing intermediate results on the call stack until it starts to return, popping those values from the stack to form the answer. Sometimes, a print statement within the method can help you see what is happening.
public static void main(String[] args) {
System.out.println(raiseToPower(3,4));
}
public static int raiseToPower(int baseVal, int exponentVal) {
if (exponentVal == 0) {
return 1;
}
int x = baseVal * raiseToPower(baseVal, exponentVal-1);
System.out.println("exponentVal = " + exponentVal + ", + x = " + x);
return x;
}
prints
exponentVal = 1, + x = 3
exponentVal = 2, + x = 9
exponentVal = 3, + x = 27
exponentVal = 4, + x = 81
81
As the recursive call unwinds when the exponentVal == 0, here is what you get
x = 1;
x = x * baseVal; // x = baseVal
x = x * baseVal; // x = baseVal ^ 2
x = x * baseVal; // x = baseVal ^ 3
x = x * baseVal; // x = baseVal ^ 4
// return x or 81
Lets take example and understand :
baseValue = 2;
exponentialValue = 3;
How we can calculate pow(2,3) , there are ways of that :
baseValue^exponentialValue ---- 2^3 = 8
baseValue x baseValue^exponentialValue-1 ---- 2x2^2 = 8
It's called recursion. The same function is being called recursively with the exponent decreasing each time, multiplied with the base value and added into result. It would run like so:
Related
good day,
what is the best way to implement the below function in java:
mod11(x) which calculates x mod 11, we assume x is either an integer or a formula. For example, mod11(14) returns 3, and mod11(3*7-30) returns 2.
I tried the below but it didn't work:
`
public static int PositiveMod(int value, int mod)
{
return ((value % mod + mod) % mod);
}
`
`
public static double PositiveMod(double value, double mod)
{
return ((value % mod + mod) % mod);
}
`
for example, i expect ((-7+1)/20) mod 11 to give out 3 but instead it gave me 10.7
like below
i = ((-7+1)/20) mod 11 = -6/9 mod 11 = 5*5 mod 11 = 3
I wrote two examples how to use it mathematical mod mathMod method and also default mod faultModCalJava mod. They will give the same result for positive numbers but for negative they have different output. More information here:
https://en.wikipedia.org/wiki/Modulo_operation
public class MainClass2 {
public static void main(String[] args) {
System.out.println("Math mod:" + mathMod(14, 11));
System.out.println("Math mod:" + mathMod((3 * 7 - 30), 11));
System.out.println("Math mod:" + mathMod(-13, 10));
System.out.println("Default Java mod: " + defaultModCalJava(14, 11));
System.out.println("Default Java mod: " + defaultModCalJava((3 * 7 - 30), 11));
System.out.println("Default Java mod:" + defaultModCalJava(-13, 10));
}
private static int mathMod(int a, int m) {
int positiveM = Math.abs(m);
int result = a % positiveM;
if (result < 0) {
result = result + positiveM;
}
return result;
}
private static int defaultModCalJava(int a, int m) {
return a % m;
}
}
Output:
Math mod:3
Math mod:2
Math mod:7
Default Java mod: 3
Default Java mod: -9
Default Java mod:-3
Your question is confusing.. the % operator is already the modulus operator, also known as remainder. ... so 14 % 11 = 3 is the same as mod11(14) = 3. There is no need to implement it as a new function.
In your equation, ((-7+1)/20) = -0.3, Its not clear why you would expect 3.
11 - 0.3 is 10.7, so that is where that answer comes from.
% is not a modulus operator. It is a remainder operator and behaves as one would expect a remainder operator to behave.
System.out.println(-10 % 3); // -3 r -1 since 3 * -3 + -1 == -10
System.out.println(10 % -3); // -3 r 1 since -3 * -3 + 1 == 10
System.out.println(-10 % -3);// 3 r -1 since 3 * -3 + -1 == -10
System.out.println(10 % 3); // 3 r 1 since 3 * 3 + 1 == 10
prints as expected
-1
1
-1
1
A true mod function for n = x mod(m) says there is some k where x - n = km
n = 20 mod(3) = 2 and k = 6 20 - 2 = 6*3
n = 20 mod(3) = -1 and k = 7 20 -(-1) = 3*7
The complete set of residues for any mod function is infinite and for the above is
n = x - mk for any integral value of k
So for the above the complete residue set would be n = 20 - 3k. Any value returned would be a legitimate result. The remainder function is simply a subset of size one of the aforementioned set of residues.
Having said that, this may help. This mod function simply corrects to the smallest positive value, assuming a positive modulus.
Mod mod11 = Mod.forModulus(11);
int k = mod11.of(-3);
System.out.println(k);
Mod mod121 = Mod.forModulus(121);
k = mod121.of(-12);
System.out.println(k);
prints
8
109
Here is a way to create mod function that just takes the target argument.
interface Mod {
int of(int value);
static Mod forModulus(int mod) {
return v-> {
int u = v % mod;
return u < 0 ? u + mod : u;
};
}
}
The above may need some tweaking either because I misunderstood your issue or because the mod function needs to be more complex to satisfy your congruency relationships.
This is the question:
You are given Q queries. Each query consists of a single number N . You can perform any of the operations on in each move:
If we take 2 integers a and b where N=a*b (a ,b cannot be equal to 1), then we can change N=max(a,b)
Decrease the value of N by 1 .
Determine the minimum number of moves required to reduce the value of to .
Input Format
The first line contains the integer Q.
The next Q lines each contain an integer,N .
Output Format
Output Q lines. Each line containing the minimum number of moves required > to reduce the value of N to 0.
I have written the following code. This code is giving some wrong answers and also giving time limit exceed error . Can you tell what are the the mistakes present in my code ? where or what I am doing wrong here?
My code:
public static int downToZero(int n) {
// Write your code here
int count1=0;
int prev_i=0;
int prev_j=0;
int next1=0;
int next2=Integer.MAX_VALUE;
if (n==0){
return 0;
}
while(n!=0){
if(n==1){
count1++;
break;
}
next1=n-1;
outerloop:
for (int i=1;i<=n;i++){
for (int j=1;j<=n;j++){
if (i*j==n){
if (prev_i ==j && prev_j==i){
break outerloop;
}
if (i !=j){
prev_i=i;
prev_j=j;
}
int max=Math.max(i,j);
if (max<next2){
next2=max;
}
}
}
}
n=Math.min(next1,next2);
count1++;
}
return count1;
}
This is part is coded for us:
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int q = Integer.parseInt(bufferedReader.readLine().trim());
for (int qItr = 0; qItr < q; qItr++) {
int n = Integer.parseInt(bufferedReader.readLine().trim());
int result = Result.downToZero(n);
bufferedWriter.write(String.valueOf(result));
bufferedWriter.newLine();
}
bufferedReader.close();
bufferedWriter.close();
}
}
Ex: it is not working for number 7176 ....
To explore all solution tree and find globally optimal solution, we must choose the best result both from all possible divisor pairs and from solution(n-1)
My weird translation to Java (ideone) uses bottom-up dynamic programming to make execution faster.
We calculate solutions for values i from 1 to n, they are written into table[i].
At first we set result into 1 + best result for previous value (table[i-1]).
Then we factor N into all pairs of divisors and check whether using already calculated result for larger divisor table[d] gives better result.
Finally we write result into the table.
Note that we can calculate table once and use it for all Q queries.
class Ideone
{
public static int makezeroDP(int n){
int[] table = new int[n+1];
table[1] = 1; table[2] = 2; table[3] = 3;
int res;
for (int i = 4; i <= n; i++) {
res = 1 + table[i-1];
int a = 2;
while (a * a <= i) {
if (i % a == 0)
res = Math.min(res, 1 + table[i / a]);
a += 1;
}
table[i] = res;
}
return table[n];
}
public static void main (String[] args) throws java.lang.Exception
{
int n = 145;//999999;
System.out.println(makezeroDP(n));
}
}
Old part
Simple implementation (sorry, in Python) gives answer 7 for 7176
def makezero(n):
if n <= 3:
return n
result = 1 + makezero(n - 1)
t = 2
while t * t <= n:
if n % t == 0:
result = min(result, 1 + makezero(n // t))
t += 1
return result
In Python it's needed to set recursion limit or change algorithm. Now use memoization, as I wrote in comments).
t = [-i for i in range(1000001)]
def makezeroMemo(n):
if t[n] > 0:
return t[n]
if t[n-1] < 0:
res = 1 + makezeroMemo(n-1)
else:
res = 1 + t[n-1]
a = 2
while a * a <= n:
if n % a == 0:
res = min(res, 1 + makezeroMemo(n // a))
a += 1
t[n] = res
return res
Bottom-up table dynamic programming. No recursion.
def makezeroDP(n):
table = [0,1,2,3] + [0]*(n-3)
for i in range(4, n+1):
res = 1 + table[i-1]
a = 2
while a * a <= i:
if i % a == 0:
res = min(res, 1 + table[i // a])
a += 1
table[i] = res
return table[n]
We can construct the directed acyclic graph quickly with a sieve and
then compute shortest paths. No trial division needed.
Time and space usage is Θ(N log N).
n_max = 1000000
successors = [[n - 1] for n in range(n_max + 1)]
for a in range(2, n_max + 1):
for b in range(a, n_max // a + 1):
successors[a * b].append(b)
table = [0]
for n in range(1, n_max + 1):
table.append(min(table[s] for s in successors[n]) + 1)
print(table[7176])
Results:
7
EDIT:
The algorithm uses Greedy approach and doesn't return optimal results, it just simplifies OP's approach. For 7176 given as example, below algorithm returns 10, I can see a shorter chain of 7176 -> 104 -> 52 -> 13 -> 12 -> 4 -> 2 -> 1 -> 0 with 8 steps, and expected answer is 7.
Let's review your problem in simple terms.
If we take 2 integers a and b where N=a*b (a ,b cannot be equal to 1), then we can change N=max(a,b)
and
Determine the minimum number of moves required to reduce the value of to .
You're looking for 2 factors of N, a and b and, if you want the minimum number of moves, this means that your maximum at each step should be minimum. We know for a fact that this minimum is reached when factors are closest to N. Let me give you an example:
36 = 1 * 36 = 2 * 18 = 3 * 12 = 4 * 9 = 6 * 6
We know that sqrt(36) = 6 and you can see that the minimum of 2 factors you can get at this step is max(6, 6) = 6. Sure, 36 is 6 squared, let me take a number without special properties, 96, with its square root rounded down to nearest integer 9.
96 = 2 * 48 = 3 * 32 = 4 * 24 = 6 * 16 = 8 * 12
You can see that your minimum value for max(a, b) is max(8, 12) = 12, which is, again, attained when factors are closest to square root.
Now let's look at the code:
for (int i=1;i<=n;i++){
for (int j=1;j<=n;j++){
if (i*j==n){
You can do this in one loop, knowing that n / i returns an integer, therefore you need to check if i * (n / i) == n. With the previous observation, we need to start at the square root, and go down, until we get to 1. If we got i and n / i as factors, we know that this pair is also the minimum you can get at this step. If no factors are found and you reach 1, which obviously is a factor of n, you have a prime number and you need to use the second instruction:
Decrease the value of N by 1 .
Note that if you go from sqrt(n) down to 1, looking for factors, if you find one, max(i, n / i) will be n / i.
Additionally, if n = 1, you take 1 step. If n = 2, you take 2 steps (2 -> 1). If n = 3, you take 3 steps (3 -> 2 -> 1). Therefore if n is 1, 2 or 3, you take n steps to go to 0. OK, less talking, more coding:
static int downToZero(int n) {
if (n == 1 || n == 2 || n == 3) return n;
int sqrt = (int) Math.sqrt(n);
for (int i = sqrt; i > 1; i--) {
if (n / i * i == n) {
return 1 + downToZero(n / i);
}
}
return 1 + downToZero(n - 1);
}
Notice that I'm stopping when i equals 2, I know that if I reach 1, it's a prime number and I need to go a step forward and look at n - 1.
However, I have tried to see the steps your algorithm and mine takes, so I've added a print statement each time n changes, and we both have the same succession: 7176, 92, 23, 22, 11, 10, 5, 4, 2, 1, which returns 10. Isn't that correct?
So, I found a solution which is working for all the test cases -
static final int LIMIT = 1_000_000;
static int[] solutions = buildSolutions();
public static int downToZero(int n) {
// Write your code here
return solutions[n];
}
static int[] buildSolutions() {
int[] solutions = new int[LIMIT + 1];
for (int i = 1; i < solutions.length; i++) {
solutions[i] = solutions[i - 1] + 1;
for (int j = 2; j * j <= i; j++) {
if (i % j == 0) {
solutions[i] = Math.min(solutions[i], solutions[i / j] + 1);
}
}
}
return solutions;
}
}
Given an integer A representing the square blocks. The height of each square block is 1. The task is to create a staircase of max height using these blocks. The first stair would require only one block, the second stair would require two blocks and so on. Find and return the maximum height of the staircase.
Your submission failed for the following input: A : 92761
Your function returned the following : 65536
The expected returned value : 430
Approach:
We are interested in the number of steps and we know that each step Si uses exactly Bi number of bricks. We can represent this problem as an equation:
n * (n + 1) / 2 = T (For Natural number series starting from 1, 2, 3, 4, 5 …)
n * (n + 1) = 2 * T
n-1 will represent our final solution because our series in problem starts from 2, 3, 4, 5…
Now, we just have to solve this equation and for that we can exploit binary search to find the solution to this equation. Lower and Higher bounds of binary search are 1 and T.
CODE
public int solve(int A) {
int l=1,h=A,T=2*A;
while(l<=h)
{
int mid=l+(h-l)/2;
if((mid*(mid+1))==T)
return mid;
if((mid*(mid+1))>T && (mid!=0 && (mid*(mid-1))<=T) )
return mid-1;
if((mid*(mid+1))>T)
h=mid-1;
else
l=mid+1;
}
return 0;
}
To expand on the comment by Matt Timmermans:
You know that for n steps, you need (n * (n + 1))/2 blocks. You want know, if given B blocks, how many steps you can create.
So you have:
(n * (n + 1))/2 = B
(n^2 + n)/2 = B
n^2 + n = 2B
n^2 + n - 2B = 0
That looks suspiciously like something for which you'd use the quadratic formula.
In this case, a=1, b=1, and c=(-2B). Plugging the numbers into the formula:
n = ((-b) + sqrt(b^2 - 4*a*c))/(2*a)
= (-1 + sqrt(1 - 4*1*(-2B)))/(2*a)
= (-1 + sqrt(1 + 8B))/2
= (sqrt(1 + 8B) - 1)/2
So if you have 5050 blocks, you get:
n = (sqrt(1 + 40400) - 1)/2
= (sqrt(40401) - 1)/2
= (201 - 1)/2
= 100
Try it with the quadratic formula calculator. Use 1 for the value of a and b, and replace c with negative two times the number of blocks you're given. So in the example above, c would be -10100.
In your program, since you can't have a partial step, you'd want to truncate the result.
Why are you using all these formulas? A simple while() loop should do the trick, eventually, it's just a simple Gaussian Sum ..
public static int calculateStairs(int blocks) {
int lastHeight = 0;
int sum = 0;
int currentHeight = 0; //number of bricks / level
while (sum <= blocks) {
lastHeight = currentHeight;
currentHeight++;
sum += currentHeight;
}
return lastHeight;
}
So this should do the job as it also returns the expected value. Correct me if im wrong.
public int solve(int blocks) {
int current; //Create Variables
for (int x = 0; x < Integer.MAX_VALUE; x++) { //Increment until return
current = 0; //Set current to 0
//Implementation of the Gauss sum
for (int i = 1; i <= x; i++) { //Sum up [1,*current height*]
current += i;
} //Now we have the amount of blocks required for the current height
//Now we check if the amount of blocks is bigger than
// the wanted amount, and if so we return the last one
if (current > blocks) {
return x - 1;
}
}
return current;
}
I have the following code:
public static void main(String[] args) {
int a = 3;
int b = 7;
int x = b; // x=b
int res = a; // res = a
int y = 1;
int invariant = 0;
System.out.println("a|b|x|y|res|invariant");
while (x > 0) {
if (x % 2 == 0) {
y = 2 * y;
x = x / 2;
} else {
res = res + y;
y = 2 * y;
x = (x - 1) / 2;
}
invariant = y + 2;
String output = String.format("%d|%d|%d|%d|%d|%d", a,b,x,y,res,invariant);
System.out.println(output);
}
// < res = a + b >
}
Which gives the following output:
a|b|x|y|res|invariant
3|7|3|2|4|4
3|7|1|4|6|6
3|7|0|8|10|10
However, if I change the numbers, the invariant isn't equal to the res anymore. Therefore my loop invariant for this problem is not correct.
I'm struggling really hard to find the correct loop invariant and would be glad if there's any hint that someone can give me.
My first impression after looking into the code and my results is that the loop invariant changes based on a and b. Let's say both a and b are odd numbers as they are in my example, then my Loop invariant is correct (at least it seems like it)
Is it correct to assume a loop variant like the following?
< res = y - 2 && a % 2 != 0 && b % 2 != 0 >
I did use different numbers and it seems like anytime I change them there's a different loop invariant and I struggle to find any pattern whatsoever.
I would really appreciate if someone can give me a hint or a general idea on how to solve this.
Thanks
This loop computes the sum a+b.
res is initialized to a.
Then, in each iteration of the loop, the next bit of the binary representation of b (starting with the least significant bit) is added to res, until the loop ends and res holds a+b.
How does it work:
x is initialized to b. In each iteration you eliminate the least significant bit. If that bit is 0, you simply divide x by 2. If it's 1, you subtract 1 and divide by 2 (actually it would be sufficient to divide by 2, since (x-1)/2==x/2 when x is an odd int). Only when you encounter a 1 bit, you have to add it (multiplied by the correct power of 2) to the result. y Holds the correct power of 2.
In your a=3, b=7 example, the binary representation of b is 111
In the first iteration, the value of res is a + 1 (binary) == a + 1 = 4
In the second iteration, the value of res is a + 11 (binary) == a + 3 = 6
In the last iteration, the value of res is a + 111 (binary) == a + 7 == 10
You could write the invariant as:
invariant = a + (b & (y - 1));
This takes advantage of the fact the at the end of the i'th iteration (i starting from 1), y holds 2^i, so y - 1 == 2^i - 1 is a number whose binary representation is i 1 bits (i.e. 11...11 with i bits). When you & this number with b, you get the i least significant bits of b.
I am solving a staircase problem and came up with multiple solutions in mind. It looks like below:
Question: You will be given number of stairs say N. What is the maximum step you can make?
For N = 5, The maximum step you can make is 2 because
5 = 1 + 2 + 2
Similarly for 8, its, 8 = 1 + 2 + 3 + 2, maximum step is 3
Similarly for 16, its, 16 = 1 + 2 + 3 + 4 + 5 + 1, maximum step is 5.
When the next number is less than previous then the series will stop.
Clearly, The maximum step is maximum number in the series.
Solution 1:
I came up with a simple solution. It works fine but not optimized.
Below is the following code:
public static long stairCase(long N) {
long i = 1;
long curr = N;
while (i < N) {
curr = curr - i;
if (i >= curr) {
return i;
}
i = i + 1;
}
return i;
}
Solution 2:
Then i figured out that its n(n+1) / 2. So, if i put n(n+1)/2 = no. of
Stairs.I cant get the solution by calculating its roots and taking
highest of the roots. My Code looks like below but it doesn't works
for N = 16 and many other cases.
int b = 1;
int var = (1) - (4 * -c);
double temp1 = Math.sqrt(var);
double root1 = (-b + temp1) / (2 * a);
double root2 = (-b - temp1) / (2 * a);
double root1Abs = Math.abs(root1);
double root2Abs = Math.abs(root2);
return (long) (root1Abs > root2Abs ? Math.floor(root1Abs) : Math
.floor(root2Abs));
Solution 3:
I came up with another solution but still its not working for N = 4
and many other cases. Below is my code:
double answer = Math.sqrt(c * 2);
return (long) (Math.floor(answer));
Does Anyone have the optimized solutions(preferably in constant time) because the input is too big(long).
m = number of stair
n = result
The equation is
n * (n+1) < 2m
The solution is
n < (sqrt(8*m+1)-1)/2
We try to find maximum integer so
n = floor((sqrt(8*m+1)-1)/2)
The Java Code:
import java.io.*;
public class Solution {
public static int staircase(int m){
return (int) Math.floor((Math.sqrt(8*(double)m+1)-1)/2);
}
public static void main(String[] args){
System.out.println("Result:"+staircase(16));
}
}
Actually I figured the solution by myself ..I should use 2* c
int a = 1;
int b = 1;
int var = (1) - (4 * -2 * c);
double temp1 = Math.sqrt(var);
double root1 = (-b + temp1) / (2 * a);
double root2 = (-b - temp1) / (2 * a);
return (long) (root1 > root2 ? Math.floor(root1) : Math.floor(root2));