How should I go about solving this recursion without trial and error - c++

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

Related

A many-to-one mapping in the natural domain using discrete input variables?

I would like to find a mapping f:X --> N, with multiple discrete natural variables X of varying dimension, where f produces a unique number between 0 to the multiplication of all dimensions. For example. Assume X = {a,b,c}, with dimensions |a| = 2, |b| = 3, |c| = 2. f should produce 0 to 12 (2*3*2).
a b c | f(X)
0 0 0 | 0
0 0 1 | 1
0 1 0 | 2
0 1 1 | 3
0 2 0 | 4
0 2 1 | 5
1 0 0 | 6
1 0 1 | 7
1 1 0 | 8
1 1 1 | 9
1 2 0 | 10
1 2 1 | 11
This is easy when all dimensions are equal. Assume binary for example:
f(a=1,b=0,c=1) = 1*2^2 + 0*2^1 + 1*2^0 = 5
Using this naively with varying dimensions we would get overlapping values:
f(a=0,b=1,c=1) = 0*2^2 + 1*3^1 + 1*2^2 = 4
f(a=1,b=0,c=0) = 1*2^2 + 0*3^1 + 0*2^2 = 4
A computationally fast function is preferred as I intend to use/implement it in C++. Any help is appreciated!
Ok, the most important part here is math and algorythmics. You have variable dimensions of size (from least order to most one) d0, d1, ... ,dn. A tuple (x0, x1, ... , xn) with xi < di will represent the following number: x0 + d0 * x1 + ... + d0 * d1 * ... * dn-1 * xn
In pseudo-code, I would write:
result = 0
loop for i=n to 0 step -1
result = result * d[i] + x[i]
To implement it in C++, my advice would be to create a class where the constructor would take the number of dimensions and the dimensions itself (or simply a vector<int> containing the dimensions), and a method that would accept an array or a vector of same size containing the values. Optionaly, you could control that no input value is greater than its dimension.
A possible C++ implementation could be:
class F {
vector<int> dims;
public:
F(vector<int> d) : dims(d) {}
int to_int(vector<int> x) {
if (x.size() != dims.size()) {
throw std::invalid_argument("Wrong size");
}
int result = 0;
for (int i = dims.size() - 1; i >= 0; i--) {
if (x[i] >= dims[i]) {
throw std::invalid_argument("Value >= dimension");
}
result = result * dims[i] + x[i];
}
return result;
}
};

acending repetitious function without array 1 22 333 4444 55555 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
F is a function that number x has been repeated in an ascending order f(x).
x : 1 2 3 4 5 6 7 8 9 10
f(x): 1 2 2 3 3 3 4 4 4 4
my function gets 'x' and gives 'f(x)' and it has to do it without array but it goes wrong in high numbers.
int main()
{
int n;
cin>>n;
int i=1,a=1;
if(n==1)
cout<<'1';
else{
while(true){
a++;
i=i+a;
if(i>=n)
break;
}
}
cout<<a;
return 0;
}
TL;DR
f(x) = floor(0.5 + sqrt(1 + 8 * (x - 1)) / 2)
Explanation
Well, since this is a mathematical problem, just solve it with math ;)
One thing to notice is the correlation between the table and the triangular numbers:
h(x) = sum(range(1, x)) = x*(x + 1)/2 //triangular number
x 1 2 3 4 5 6 7 8 9 10
f(x) 1 2 2 3 3 3 4 4 4 4
h(f(x)) 1 3 3 6 6 6 10 10 10 10
So how does that help us? Well, we can write a new equation:
h(f(x)) = x | x = max({n | f(n) = f(x)})
And logically for the inverse the following should apply:
h^-1(x) = f(x)
No we've got two options:
Call it a day and just solve the rest via brute-force:
i = 1
sum = 0
while sum < x:
sum += i
i++
return i - 1
Or build our function h^-1(x):
h(x) = y = (x+1)x/2
h^-1(y) = x with h(x) = y
x ^ 2 + x - 2y = 0
solve for x using the quadratic formula:
x = 0.5 +/- sqrt(1 + 8y) / 2
Now this formula still lacks a few things:
we get two results, one of which is negative. We can just throw the negative result away, so +/- turns into +
this formula is 0-based. To be honest, I'm still trying to figure out why. Solution: simply decrement y by 1 to get the proper result
while this formula returns the correct result for the matching numbers, i.e. y = 3 -> x = 3, it returns floating-point numbers for other input, so we'll have to round down appropriately
Putting it together:
f(x) = floor(0.5 + sqrt(1 + 8 * (x - 1)) / 2)
int f(int x) {
return (x * (x + 1)) / 2;
}
int main() {
int n;
cin >> n;
int left = 1, right = n;
while(left < right) {
int mid = left + (right - left) / 2;
int val = f(mid);
if(val >= n) {
right = mid;
}
else {
left = mid + 1;
}
}
cout << left;
return 0;
}
Use binary search. Right now I am in mobile. I will add the explanation later if needed. Let me know if you don't understand anything.

Can't finish a mathematical project

I am new to coding and I am finding this site really helpful. So I have been trying to solve this problem and I am getting erroneous results, so I would be really grateful if you could help me out here.
The Problem: Find the sum of all the multiples of 3 or 5 below 1000. (For example, if we list all the positive integers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9, which sum is 23.)
My code:
count = 0
count1 = 0
for x in range(1000):
if x % 5 == 0:
count = count + x
if x % 3 == 0:
count1 = count1 + x
print count1 + count
What am I doing wrong?
Thanks in advance!
You want an elif in your code so you don't count the same x twice but a simpler way is to use an or with a single count variable:
count = 0
for x in range(1000):
if x % 5 == 0 or x % 3 == 0:
count += x
Which can be done using sum:
print(sum(x for x in range(3, 1000) if not x % 5 or not x % 3))
For completeness, a working version using your own code:
count = 0
count1 = 0
for x in range(1000):
if x % 5 == 0:
count += x
elif x % 3 == 0:
count1 += x
print count1 + count
ifs are always evaluated; so, for instance, when x is 15 it is evenly divisible by 5 and 3 so you count 15 twice, an elif is only evaluated if the previous if/elif evaluates to False so using elif only one occurrence of x will be added to the total.
Below 10 there is no number being multiple of both 5 and 3. But below 1000 there are several numbers divided exactly by 3 and 5 also (15, 45 ...).
So you need:
count=0
for x in range(1000):
if x % 5 == 0 or x % 3 == 0:
count=count + x
print count

Partitioning arrays by index

I am fairly new to C++, and am struggling through a problem that seems to have a solid solution but I just can't seem to find it. I have a contiguous array of ints starting at zero:
int i[6] = { 0, 1, 2, 3, 4, 5 }; // this is actually from an iterator
I would like to partition the array into groups of three. The design is to have two methods, j and k, such that given an i they will return the other two elements from the same group of three. For example:
i j(i) k(i)
0 1 2
1 0 2
2 0 1
3 4 5
4 3 5
5 3 4
The solution seems to involve summing the i with its value mod three and either plus or minus one, but I can't quite seem to work out the logic.
This should work:
int d = i % 3;
int j = i - d + ( d == 0 );
int k = i - d + 2 - ( d == 2 );
or following statement for k could be more readable:
int k = i - d + ( d == 2 ? 1 : 2 );
This should do it:
int j(int i)
{
int div = i / 3;
if (i%3 != 0)
return 3*div;
else
return 3*div+1;
}
int k(int i)
{
int div = i / 3;
if (i%3 != 2)
return 3*div+2;
else
return 3*div+1;
}
Test.
If you want shorter functions:
int j(int i)
{
return i/3*3 + (i%3 ? 0 : 1);
}
int k(int i)
{
return i/3*3 + (i%3-2 ? 2 : 1);
}
Well, first, notice that
j(i) == j(3+i) == j(6+i) == j(9+i) == ...
k(i) == k(3+i) == k(6+i) == k(9+i) == ...
In other words, you only need to find a formula for
j(i), i = 0, 1, 2
k(i), i = 0, 1, 2
and then for the rest of the cases simply plug in i mod 3.
From there, you'll have trouble finding a simple formula because your "rotation" isn't standard. Instead of
i j(i) k(i)
0 1 2
1 2 0
2 0 1
for which the formula would have been
j(i) = (i + 1) % 3
k(i) = (i + 2) % 3
you have
i j(i) k(i)
0 1 2
1 0 1
2 0 2
for which the only formula I can think of at the moment is
j(i) = (i == 0 ? 1 : 0)
k(i) = (i == 1 ? 1 : 2)
If the values of your array (let's call it arr, not i in order to avoid confusion with the index i) do not coincide with their respective index, you have to perform a reverse lookup to figure out their index first. I propose using an std::map<int,size_t> or an std::unordered_map<int,size_t>.
That structure reflects the inverse of arr and you can extra the index for a particular value with its subscript operator or the at member function. From then, you can operate purely on the indices, and use modulo (%) to access the previous and the next element as suggested in the other answers.

C++ get every number separately

I have a range of numbers from 100 to 999. I need to get every number separately of it and check whether it can be divided by 2. For example:
232
2 divided by 2 = 1 = true
3 divided by 2 = 1.5 = false
2 divided by 2 = 1 = true
and so on.
To get the first number all I have to do is to divide the entire number by 100.
int x = 256;
int k = x/100;
so x would hold a value of 2.
Now, is there a way to check those other ones? Because k = x/10; would already be 25.
Try this:
int x = 256;
int i = x / 100; // i is 2
int j = (x % 100) / 10; // j is 5
int k = (x % 10); // k is 6
maybe look into integer division and the modulo.
int k1 = (x / 10) % 10 // "10s"
int k2 = ( x / 100 ) % 10 // "100s"
//etc etc
Use modulo to get the last digit of the number, then divide by ten to discard the last digit.
Repeat while the number is non-zero.
What you need is the modulus operator %. It does a division and returns the reminder.
1 % 2 = 1
2 % 2 = 0
3 % 2 = 1
4 % 2 = 0
...
eg. take 232:
int num = 232;
int at_ones_place = num % 10;
int at_tens_place = ( num /10 ) % 10 ;
int at_hundreds_place = (num /100);