Multiplication by recursion - how are values added? - c++

I am trying to understand what is happening in my recursion step return x + times(x, y-1).
Specifically times(x, y-1) Since there is no equation in the function what is happening in the recursion? I don't see how the values are added.
#include <iostream>
using namespace std;
int times(int x, int y)
{
if (x == 0 || y == 0)
return 0;
else if (y == 1)
return x;
else
return x + times(x, y - 1);
}
int main()
{
int x, y;
cout << "Enter two numbers to be multiplied seperated by a space: ";
cin >> x >> y;
cout << "The product is " << times(x, y) << endl;
return 0;
}

The best way to understand recursion is to write all the stack trace on paper.
Let's take an example of times(3, 2):
Call 1: times(3, 2) -> returns 6
Call 2: 3 + times(3, 1) -> returns (3 + 3), that is 6
Call 3: times(3, 1) -> returns 3
So, the final answer is 6.
x + times(x, y-1): It's a way of representing multiplication using addition. For example:
1) 3 * 2 = (3 + 3)
2) 4 * 3 = (4 + 4 + 4 + 4)
#dxiv mentioned it perfectly, a * n = a + a * (n - 1).

Related

Solution for equation of a line with 2 variables ax + by = c works in one case but fails in other case

I am trying to solve ax + by = n.
When I put n = 7, it solves the equation correctly as X = 2 and Y = 1.
But when I put n = 1, it does not solve the equation. Even though, this equation has valid integer solution, X = 17, Y = -11. here is my full program.
#include <iostream>
using namespace std;
void PrintXY(int a, int b, int n)
{
for (int i = 0; i * a <= n; i++) {
if ((n - (i * a)) % b == 0) {
cout << "x = " << i << ", y = "
<< (n - (i * a)) / b;
return;
}
}
cout << "No solution";
}
int main()
{
int a = 2, b = 3, n = 1;
PrintXY(a, b, n);
return 0;
}
Output when n = 7:
x = 2, y = 1
Output when n = 1:
No solution
Reasoning.
2*(2) + 3*(1) - 7 = 4 + 3 - 7 = 0
2*(17) + 3*(-11) - 1 = 34 - 33 - 1 = 0
Both equations solve to give 0. But what is wrong in my program that is causing it to give "No Solution".
The problem is with the termination condition:
i*a<=n
This(n>=a*i) need not be true, and is especially not true in case of the solution (ie X=17, Y=-11). Which seems reasonable - Without any bounds(limits) on the answer(either X or Y) , how would you find the solution to a linear equation(with an infinite possible range) in a closed for loop ?

How to calculate pi with 3 decimals precision in C++?

hey guys I am trying to calculate pi using this formula:
pi = 4 · [ 1 – 1/3 + 1/5 – 1/7 + 1/9 ... + (–1)^n/(2n + 1) ]
yet i always get a zero for my output pi value and I am really confused as to where I had gone wrong. Here is my code:
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
int n;
double b = 0;
char c = 'Y';
int s = 1;
while (c == 'Y') {
cout << "Enter the value of the parameter 'n' in the Leibniz formula (or -1 to quit):" << endl;
cin >> n;
if (n != -1) {
c = 'Y';
for (int a = 1; a <= n; a++) {
s = -s;
b += 4 * (s/ (2 * a + 1));
}
cout << "The approximate value of pi using 1 term is:" << b << endl;
}
else {
c = 'N';
}
}
return 0;
}
In both C and C++, mathematical operations on integers result in an integer even if the result would be fractional in conventional mathematics. Change your int to a float or double and I suspect that it will work better.
The result is truncated to the integer value and has an integer type.
So for example: 2 / 4 results in 0 and 5 / 2 would result in 2.
NOTE if you perform an operation between a floating point value and an integer value, the result is a floating point value. So:
2.0 / 4 == 0.5
Your code seems to be complicated and int type is used in places where floating operations are expected.
Consider the following simplified example:
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
int n = 0;
double b = 0;
double s = 1; // Tytpe is changed
while (n != -1) { // there is no need for char c
cout << "Enter the value of the parameter 'n' in the Leibniz formula (or -1 to quit):" << endl;
cin >> n;
b = 0; // init b before starting the loop
s = 1; // the same for s (it can be -1 from the next user input)
// there is no need for if (n != -1) because for has condition
for (int a = 1; a <= n; a++) {
s = -s;
b += 4 * (s / (2.0 * a + 1));
}
cout << "The approximate value of pi using 1 term is:" << b << endl;
}
return 0;
}
IMPORTANT UPDATE:
To make your calculation correct (in terms of Leibniz's formula) I suggest the following changes in the for loop:
for (int a = 0; a <= n; a+=2) { // start from 0 with step 2
b += 4.0 * (s / (a + 1.0));
s = -s; // change the sign for next calculation
}
and further, consider some kind of optimization
b = 0; // do not forget about reseting b to 0 before making sum
s = 1; // set 1 in the sign
for (int a = 0; a <= n; a+=2) { // start from 0 with step 2
b += s / (a + 1.0); // no multiplication on each iteration
s = -s; // because s was initialized with 1
}
b *= 4.0; // multiply once for the whole sum
UPDATE 2
For case if precision is really important for output, final snippet can be like:
#define _USE_MATH_DEFINES
#include <cmath>
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int n = 0;
double b = 0;
double s = 1;
int prec = 0;
cout << "What precision should be used for output? (Value from 1 to 10): ";
while (prec< 1 || prec > 10)
{
cin >> prec;
}
while (true) {
cout << "Enter the value of the parameter 'n' in the Leibniz formula (or -1 to quit):" << endl;
cin >> n;
if (n == -1)
{
break; // go out the loop if user enter -1 (want to exit)
}
else if (n <= 0)
{
cout << "'n' have to be 1 or greater" << endl;
continue; // go to the next iteration to ask new 'n'
}
s = 1;
b = 1.0; // we can start from 1 (no need to claculate the first term) and make loop from 2
for (int a = 2; a < n*2; a+=2) { // start from 2 with step 2 (so n should be doubled)
s = -s; // change the sign for this iteration, because now loop started from a = 2
b += s / (a + 1.0);
}
b *= 4.0;
cout << "The approximate value of pi using 1 term is: " << setprecision(prec+1) << b << " (PI = " << M_PI << ")" << endl;
}
return 0;
}
Note:
In this version b initialized with 1.0 because the first item in the Leibniz series is always 1 (we can skip calculation, but we should change the logic for sign changes - make s = -1; or move s = -s; before summation - I choose the 2nd option).
Also I'am not sure what is "parameter 'n' in the Leibniz formula", so pay attention to condition of for loop - now (with a < n*2) it is correct for case if n is number of items in the Leibniz series to be calculated.
Along with doing integer math, you have a few other minor problems.
First, the formula is [1 - ...], not [0 - ...], so you need to initialize b to 1.0, not 0.
Second, it's supposed to be 4 * [...], but you're multiplying by 4 on every iteration of the loop, so you're getting `[0 - b1 * 4 + b2 * 4 -b3 * 4 ....].
You can distribute the multiplication if you want to, but if you do you'll need to distribute it correctly (e.g., the starting value of 1.0 would also need to be multiplied by 4).
Also note that you're not re-initializing correctly, so the second (and subsequent) times you attempt to re-compute the value, you'll get completely incorrect answers (until you fix more stuff).
You've been burned by integer division.
b += 4 * (s/ (2 * a + 1));
a is an int so the division result is an int.
A cast to double will fix it:
b += 4 * (s/ (2 * double(a) + 1));

c++ recursion that i don't understand

I don't understand why this returns a 5 when 5 is entered?
does it return a 1 each time the function can make a subtraction? and then add all those ones?
#include <iostream>
using namespace std;
int Fibonacci(int);
int Fibonacci(int x)
{
if (x == 0) return 0; // Stopping conditions
if (x == 1) return 1;
return Fibonacci(x - 1) + Fibonacci(x - 2);
}
int main() {
int num;
cin >> num;
cout << Fibonacci(num) << endl;
return 0;
}
For clarity, using a function
auto F( int x )
-> int
{ return (x <= 1? x : F(x-2)+F(x-1)); }
F(5)
→ F(3) + F(4)
→ (F(1) + F(2)) + F(4)
→ (1 + F(2)) + F(4)
→ (1 + (F(0) + F(1))) + F(4)
→ (1 + (0 + F(1))) + F(4)
→ (1 + (0 + 1)) + F(4)
→ (1 + 1) + F(4)
→ 2 + F(4)
→ 2 + (F(2) + F(3))
and so on…
0,1,1,2,3,5 are what it calculates for getting to the value for 5. When asked for any element but the first two (here indexed as a sub 0 and a sub 1) it adds the preceding two elements (those subtractions are to the indices of the sequence, not the value). A sub zero is set to 0 and a sub one to 1.

Could someone tell me any different way to make this code faster?

The code runs correctly and it does what it is supposed to do, but I was told I could make it faster by using Boolean expressions instead but would not really know where to insert them here. The problem is:
Given a sequence of n points with their coordinates, write a program remote, which calculates the value of the smallest remoteness of a point, which is outside the square. A point is outside the square, if it is neither inner to the square, nor belongs to square contour. If there are no points outside the square, your program has to output 0.
Constraints:
1 ≤ n ≤ 10000 and 1 ≤ a ≤ 1000 ;
Example:
Input:
5 4
1 2
4 6
-3 2
-2 2
4 -1
Output: 5
Could someone suggest me any technique to make the code more efficient?
int remote(int x, int y) {
int z = abs(x) + abs(y);
return z;
}
int main() {
int n, a;
int x;
int y;
cin >> n >> a;
int z=20001;
for (int i = 1; i <= n; i++) {
cin >> x >> y;
if (x > a / 2 || y > a / 2) {
if (z > remote(x, y)) {
z = remote(x, y);
}
}
}
cout << z <<endl;
return 0;
}
For one, you are calling remote twice (in some cases) needlessly.
Consider using this:
#include <algorithm>
z = std::max(z, remote(x, y));
This will also shorten and clarify the code.
Also, it's possible the divisions are slow. Try (after profiling!) replacing
x > a / 2 || y > a / 2
by
(x << 1) > a || (y << 1) > a
Note #Donnie & others claims in the comments that compilers will do the latter optimization, and they are probably correct.
I would like to show you the timings on my machine:
Version 1:
for (int i = 1; i <= n; i++) {
cin >> x >> y;
if (x > a / 2 || y > a / 2) {
if (z > remote(x, y)) {
z = remote(x, y);
}
}
}
Version 2:
for (int i = 1; i <= n; i++) {
cin >> x >> y;
/* if (x > a / 2 || y > a / 2) {
if (z > remote(x, y)) {
z = remote(x, y);
}
}
*/
}
For n=10^5, compiled with -O3 both yield 60ms. Compiled without optimization: both 60ms.
First step for optimizing is to know where your program spends time. Reading/parsing the data is the bottle neck.
You could speed up it a little bit by adding as first line to your main:
ios_base::sync_with_stdio(false);
On my machine I'm down to 20ms.
1) Assign a temporary value to the remote function:
if (x > a / 2 || y > a / 2)
{
const int r = remote(x,y);
if (z > r)
{
z = r;
}
}
2) Replace the call to remote with the contents of remote, removing the overhead of a function call:
if (x > a / 2 || y > a / 2)
{
const int r = abs(x) + abs(y);
if (z > r)
{
z = r;
}
}
3) Replace a / 2 with a constant temporary variable:
const int midpoint = a >> 1;
if (x > midpoint || y > midpoint)
4) Change compiler optimization level to high - for speed.
5) The bottleneck is now in the input statement. Any gain by optimizing the remainder of the loop is wasted by the Input time. There is no more Return On Investment for further changes.

Finding MAX of numbers without conditional IF statements c++ [duplicate]

This question already has answers here:
Mathematically Find Max Value without Conditional Comparison
(18 answers)
Closed 9 years ago.
So i have too get two numbers from user input, and find the max of the two numbers without using if statements.
The class is a beginner class, and we have too use what we already know. I kinda worked something out, but it only works if the numbers are inputted with the max number first.
#include <iostream>
using namespace std;
int main()
{
int x = 0, y = 0, max = 0;
int smallest, largest;
cout << "Please enter 2 integer numbers, and i will show you which one is larger: ";
cin >> x >> y;
smallest = (x < y == 1) + (x - 1);
smallest = (y < x == 1) + (y - 1);
largest = (x < y == 1) + (y - 1);
largest = (y > x == 1) + (x + 1 - 1);
cout << "Smallest: " << smallest << endl;
cout << "Largest: " << largest << endl;
return 0;
}
Thats what i have so far, but after putting different test data in, i found out it only works for numbers such as 4,5 or 6,7. But numbers with more then 2 spaces between eachother they dont such as, 4,8 or 5, 7. Any help would be appreciated.
I saw this question in Cracking the Coding interview book.
Let’s try to solve this by “re-wording” the problem We will re-word the problem until we get something that has removed all if statements
Rewording 1: If a > b, return a; else, return b
Rewording 2: If (a - b) is negative, return b; else, return a
Rewording 3: If (a - b) is negative, let k = 1; else, let k = 0 Return a - k * (a - b)
Rewording 4: Let c = a - b Let k = the most significant bit of c Return a - k * c
int getMax(int a, int b) {
int c = a - b;
int k = (c >> ((sizeof(int) * CHAR_BIT) - 1)) & 0x1;
int max = a - k * c;
return max;
}
Source: http://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/098478280X
Edit: This code works even when a-b overflows.
Let k equal the sign of a-b such that if a-b >=0, then k is 1, else k=0.Let q be the inverse of k. Above code overflows when a is positive or b is negative, or the other way around. If a and b have different signs, then we want the k to equal sign(a).
/* Flips 1 to 0 and vice-versa */
public static int flip(int bit){
return 1^bit;
}
/* returns 1 if a is positive, and 0 if a is negative */
public static int sign(int a){
return flip((a >> ((sizeof(int) * CHAR_BIT) - 1)) & 0x1);
}
public static int getMax(int a, int b){
int c = a - b;
int sa = sign(a-b); // if a>=0, then 1 else 0
int sb = sign(a-b); // if b>=1, then 1 else 0
int sc = sign(c); // depends on whether or not a-b overflows
/* If a and b have different signs, then k = sign(a) */
int use_sign_of_a = sa ^ sb;
/* If a and b have the same sign, then k = sign(a - b) */
int use_sign_of_c = flip(sa ^ sb);
int k = use_sign_of_a * sa + use_sign_of_c * sc;
int q = flip(k); //opposite of k
return a * k + b * q;
}
Here is a funny solution:
int max_num = (x>y)*x + (y>=x)*y;
Assuming that you have covered bitwise operators already you can do this:
max = a-((a-b)&((a-b)>>(sizeof(int)*8-1)));
This is based off of the solution from Mathematically Find Max Value without Conditional Comparison that #user93353 pointed out in the comments above.
This may be overkill if you really are just trying to avoid if statements, not comparisons in general.
You can try this code to find max and min for two input variables.
((a > b) && (max = a)) || (max=b);
((a < b) && (min = a)) || (min=b);
For three input variables you can use similar method like this:
int main()
{
int a = 10, b = 9 , c = 8;
cin >> a >> b >> c;
int max = a, min = a;
// For Max
((a > b) && (a > c) && (max=a)) ||
((b > c) && (b > a) && (max=b)) ||
(max=c) ;
// For min
((a < b) && (a < c) && (min=a)) ||
((b < c) && (b < a) && (min=b)) ||
(min=c) ;
cout << "max = " << max;
cout << "and min = " << min;
return 1;
}
One run is:
:~$ ./a.out
1
2
3
max = 3 and min = 1
Edit
Thanks to #Tony D: This code will fail for negative numbers.
One may try this for negative numbers for two inputs to find max(not sure for this):
((a > b) && ( a > 0 && (max = a))) || ((b > a) && (max = b)) || (max = a);