I got an exam two days from now and my professor gave us an old exam with the solutions however after going over this problem countless of times I can't figure out how in the world the answer is the answer.
int recursive (int n) {
if (n < 10) return n;
return 100 * recursive (n / 100) + 10 * (n % 10);
}
int main(){
cout << recursive (19683) << endl;
return 0;
}
The answer should print out 16030 but I have no idea of how it gets that. I do
100*196+10*3 = 19630
Then I do
100*1+10*3 = 130
which is completely wrong would appreciate it if someone knew how to get to that answer
The first call (recursive(19683)) returns:
100 * recursive(196) + 10*3
The second call (recursive(196)) returns:
100 * recursive(1) + 10*6
The third call (recursive(1)) returns 1 directly. Substituting back, one gets:
100 * (100 * 1 + 60) + 30 = 10000 + 6000 + 30 = 16030
Back in high school we were taught to be able to desk check our code. Desk checking is where you compute, by hand, the result of every step.
int recursive (int n) {
if (n < 10) return n;
return 100 * recursive (n / 100) + 10 * (n % 10);
}
Pass this 19683
recursive(19683)
19683 < 10 is false
return 100 * recursive(196) + 10 * (19683 % 10 -> 3)
recursive(196)
196 < 10 is false
return 100 * recursive(1) + 10 * (196 % 10 -> 6)
recursive(1)
1 < 10 is true, return 1
substitute recursive(1) = 1 into earlier equation...
return 100 * 1 * 60 -> 160
substitute recursive(196) = 160 into earlier equation...
return 100 * 160 + 10 * 3 -> 16030
recursive(19683) = 100 * recursive(196) + 10 * 3
recursive(196) = 100 * recursive(1) + 10 * 6
recursive(1) = 1
Now back-fill the answers
recursive(196) = 100 + 60
recursive(19683) = 100 * 160 + 30 = 16030
In order to understand what's happening, look at a a simpler example of recursion, such as reversing a string. There's a good explanation of how recursion works in the answers to this question: -
Reverse a string using recursion
Once that makes sense to you, you should find understanding the example question you pose much easier.
Related
Please, name thise methods.I new there, could you provide some reference?
char Time[] = "TIME:00:00:00";
void loop() {
Date[5] = gps.date.day() / 10 + 48;
Date[6] = gps.date.day() % 10 + 48;
Date[8] = gps.date.month() / 10 + 48; //Please, name thise methods.
Date[9] = gps.date.month() % 10 + 48;
Date[13] =(gps.date.year() / 10) % 10 + 48;
Date[14] = gps.date.year() % 10 + 48;}
Adding 48 is a way to convert a digit to a corresponding character. ASCII codes of digits start with 48 for '0'. so 5 + '0' is '5'.
x / 10 is division of x by 10. with integer division you get 2 from 23
x % 10 is modulo of x by 10. you get the remainder of division of x by 10. so you get 3 from 23.
So the code in question converts time digit by digit to a printable text.
Let's say I have 15 elements. I want to group them such a way that:
group1 = 1 - 5
group2 = 6 - 9
group3 = 10 - 12
group4 = 13 - 14
group5 = 15
This way I'll get elements in each group as below:
group1 = 5
group2 = 4
group3 = 3
group4 = 2
group5 = 1
As you can see loop interval is decreasing.
I took 15 just for an example. In actual programme it's user driven parameter which can be anything (hopefully few thousand).
Now what I'm looking for is:
Whatever is in group1 should have variable "loop" value 0, group2 should have 1, group3 should have 2 and so on... "loop" is an int variable which is being used to calculate some other stuff.
Let's put in other words too
I have an int variable called "loop". I want to assign value to it such a way that:
First n frames loop value 0 next (n -1) frames loop value 1 then next (n - 2) frames loop value 2 all the way to loop value (n - 1)
Let's say I have 15 frames on my timeline.
So n will be 5 ====>>>>> (5 + 4 + 3 + 2 + 1 = 15; as interval is decreasing by 1)
then
first 5 frames(1 - 5) loop is 0 then next 4 frames(6 - 9) loop is 1 then next 3 frames(10 - 12) loop is 2 then next 2 frames(13 - 14) loop is 3 and for last frame(15) loop is 4.
frames "loop" value
1 - 5 => 0
6 - 9 => 1
10 - 12 => 2
13 - 14 => 3
15 => 4
I've tried with modulo(%). But the issue is on frame 12 loop is 2 so (12 % (5 - 2)) remainder is 0 so it increments loop value.
The following lines are sample code which is running inside a solver. #loop is by default 0 and #Frame is current processing frame number.
int loopint = 5 - #loop;
if (#Frame % loopint == 0)
#loop += 1;
If I understand this correctly, then
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[]) {
int n = atoi(argv[1]);
for(int i = 1; i <= n; ++i) {
printf("%d: %f\n", i, ceil((sqrt(8 * (n - i + 1) + 1) - 1) / 2));
}
}
is an implementation in C.
The math behind this is as follows: The 1 + 2 + 3 + 4 + 5 you have there is a Gauß sum, which has a closed form S = n * (n + 1) / 2 for n terms. Solving this for n, we get
n = (sqrt(8 * S + 1) - 1) / 2
Rounding this upward would give us the solution if you wanted the short stretches at the beginning, that is to say 1, 2, 2, 3, 3, 3, ...
Since you want the stretches to become progressively shorter, we have to invert the order, so S becomes (n - S + 1). Therefore the formula up there.
EDIT: Note that unless the number of elements in your data set fits the n * (n+1) / 2 pattern precisely, you will have shorter stretches either at the beginning or in the end. This implementation places the irregular stretch at the beginning. If you want them at the end,
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[]) {
int n = atoi(argv[1]);
int n2 = (int) ceil((sqrt(8 * n + 1) - 1) / 2);
int upper = n2 * (n2 + 1) / 2;
for(int i = 1; i <= n; ++i) {
printf("%d: %f\n", i, n2 - ceil((sqrt(8 * (upper - i + 1) + 1) - 1) / 2));
}
}
does it. This calculates the next such number beyond your element count, then calculates the numbers you would have if you had that many elements.
int sum_down(int x)
{
if (x >= 0)
{
x = x - 1;
int y = x + sum_down(x);
return y + sum_down(x);
}
else
{
return 1;
}
}
What is this smallest integer value of the parameter x, so that the returned value is greater than 1.000.000 ?
Right now I am just doing it by trial and error and since this question is asked via a paper format. I don't think I will have enough time to do trial and error. Question is, how do you guys visualise this quickly such that it can be solved easily. Thanks guys and I am new to programming so thanks in advance!
The recursion logic:
x = x - 1;
int y = x + sum_down(x);
return y + sum_down(x);
can be simplified to:
x = x - 1;
int y = x + sum_down(x) + sum_down(x);
return y;
which can be simplified to:
int y = (x-1) + sum_down(x-1) + sum_down(x-1);
return y;
which can be simplified to:
return (x-1) + 2*sum_down(x-1);
Put in mathematical form,
f(N) = (N-1) + 2*f(N-1)
with the recursion terminating when N is -1. f(-1) = 1.
Hence,
f(0) = -1 + 2*1 = 1
f(1) = 0 + 2*1 = 2
f(2) = 1 + 2*2 = 5
...
f(18) = 17 + 2*f(17) = 524269
f(19) = 18 + 2*524269 = 1048556
Your program can be written this way (sorry about c#):
public static void Main()
{
int i = 0;
int j = 0;
do
{
i++;
j = sum_down(i);
Console.Out.WriteLine("j:" + j);
} while (j < 1000000);
Console.Out.WriteLine("i:" + i);
}
static int sum_down(int x)
{
if (x >= 0)
{
return x - 1 + 2 * sum_down(x - 1);
}
else
{
return 1;
}
}
So at first iteration you'll get 2, then 5, then 12... So you can neglect the x-1 part since it'll stay little compared to the multiplication.
So we have:
i = 1 => sum_down ~= 4 (real is 2)
i = 2 => sum_down ~= 8 (real is 5)
i = 3 => sum_down ~= 16 (real is 12)
i = 4 => sum_down ~= 32 (real is 27)
i = 5 => sum_down ~= 64 (real is 58)
So we can say that sum_down(x) ~= 2^x+1. Then it's just basic math with 2^x+1 < 1 000 000 which is 19.
A bit late, but it's not that hard to get an exact non-recursive formula.
Write it up mathematically, as explained in other answers already:
f(-1) = 1
f(x) = 2*f(x-1) + x-1
This is the same as
f(-1) = 1
f(x+1) = 2*f(x) + x
(just switched from x and x-1 to x+1 and x, difference 1 in both cases)
The first few x and f(x) are:
x: -1 0 1 2 3 4
f(x): 1 1 2 5 12 27
And while there are many arbitrary complicated ways to transform this into a non-recursive formula, with easy ones it often helps to write up what the difference is between each two elements:
x: -1 0 1 2 3 4
f(x): 1 1 2 5 12 27
0 1 3 7 15
So, for some x
f(x+1) - f(x) = 2^(x+1) - 1
f(x+2) - f(x) = (f(x+2) - f(x+1)) + (f(x+1) - f(x)) = 2^(x+2) + 2^(x+1) - 2
f(x+n) - f(x) = sum[0<=i<n](2^(x+1+i)) - n
With eg. a x=0 inserted, to make f(x+n) to f(n):
f(x+n) - f(x) = sum[0<=i<n](2^(x+1+i)) - n
f(0+n) - f(0) = sum[0<=i<n](2^(0+1+i)) - n
f(n) - 1 = sum[0<=i<n](2^(i+1)) - n
f(n) = sum[0<=i<n](2^(i+1)) - n + 1
f(n) = sum[0<i<=n](2^i) - n + 1
f(n) = (2^(n+1) - 2) - n + 1
f(n) = 2^(n+1) - n - 1
No recursion anymore.
How about this :
int x = 0;
while (sum_down(x) <= 1000000)
{
x++;
}
The loop increments x until the result of sum_down(x) is superior to 1.000.000.
Edit : The result would be 19.
While trying to understand and simplify the recursion logic behind the sum_down() function is enlightening and informative, this snippet tend to be logical and pragmatic in that it does not try and solve the problem in terms of context, but in terms of results.
Two lines of Python code to answer your question:
>>> from itertools import * # no code but needed for dropwhile() and count()
Define the recursive function (See R Sahu's answer)
>>> f = lambda x: 1 if x<0 else (x-1) + 2*f(x-1)
Then use the dropwhile() function to remove elements from the list [0, 1, 2, 3, ....] for which f(x)<=1000000, resulting in a list of integers for which f(x) > 1000000. Note: count() returns an infinite "list" of [0, 1, 2, ....]
The dropwhile() function returns a Python generator so we use next() to get the first value of the list:
>>> next(dropwhile(lambda x: f(x)<=1000000, count()))
19
I am creating a random number generator and whenever I run the current code block I always get a few numbers that go over the intended limit. The way it works is that I have a set of numbers that are randomly generated that go from 36-75, With adjusted numbers that are 5 higher and 5 lower than the original number. For example I will end up with numbers above 75. The highest being 105.
Here is just one of the 6 numbers.
//Displays picks for Number 4
pick4 = (rand() % 75) + 36;
if (pick4 == pick3)
pick4 = (rand() % 75) + 36;
if (pick4 + 5 < 75 + 1)
{
if (pick4 - 5 > 0)
{
adjHighPick4 = pick4 + 5;
adjLowPick4 = pick4 - 5;
}
}
When you want to get a random integer from A to B, you just need a random integer from 0 to B-A, to which you add A. So, instead of rand() % 75 + 36, you should write rand() % 39 + 36 (A=36, B=75, B-A=39)
Consider number 194 declared as type int
Is it possible to obtain it's digits permutations like other ints efficiently?
Number: 194
419 int
491 int
914 int
941 int
I am using the next_permutation however it only works with arrays. So I thought it wouldn't be wise to convert int to an int array (?!) then obtain the permutation as an array and convert it to it.
Any suggestions?
Permuting the digits is basically a string-operation, not a (simple) mathematical operation. Converting to an array (string) and then using next_permutation() sounds more sensible than trying to do it mathematically.
Here's the mathematical version - without intermediate values saved:
int a = 194;
int b = (a / 100) * 100 + (a % 10) * 10 + ((a / 10) % 10) * 1; // 149
int c = (a % 10) * 100 + ((a / 10) % 10) * 10 + (a / 100) * 1; // 491
int d = (a % 10) * 100 + (a / 100) * 10 + ((a / 10) % 10) * 1; // 419
int e = ((a / 10) % 10) * 100 + (a / 100) * 10 + (a % 10) * 1; // 914
int f = ((a / 10) % 10) * 100 + (a % 10) * 10 + (a / 100) * 1; // 941
With intermediate values, it's a little easier to see what's going on (except that I generated different assignments for b through f this time).
int a = 194;
int d1 = a / 100;
int d2 = (a / 10) % 10;
int d3 = a % 10;
int a = d1 * 100 + d2 * 10 + d3 * 1; // 194
int b = d1 * 100 + d3 * 10 + d2 * 1; // 149
int c = d2 * 100 + d1 * 10 + d3 * 1; // 914
int d = d2 * 100 + d3 * 10 + d1 * 1; // 941
int e = d3 * 100 + d1 * 10 + d2 * 1; // 419
int f = d3 * 100 + d2 * 10 + d1 * 1; // 491
Use the next_permutation() mechanism; it will generalize to 4-digit and 5-digit and N-digit numbers where this will not.
You'd first have to extract each decimal place's value first: either by converting it to a character array (itoa()) or by writing a small for loop that divides the number by powers of 10. Once you have the digits separated, you can write a loop to generate the permutations.
Getting the permutations of the decimal digits will require you to interact with the number as a decimal, so power-of-2 manipulations are probably not going to help much here.
My suggestion would be:
1. Convert number to string
2. Set up the string as a circular buffer
3. Step through the buffer progressively (each increment of the index into the circular buffer will give you one permutation)
4. Reconstruct the number from the "new" arrangement of the characters representing the digits
5. Repeat for the length of the string.
Unless you are running in a slow/resource-constrained environment, I wouldn't try to overthink the problem beyond this.
Edit:
As pointed out in the comments this doesn't generate all permutations, to do so would require adding another step at the end where the process is repeated but with progressively larger increments to the index variable.