I want to make sure that all 3 conditions result in the same answer before executing a control block:
#include <iostream>
#include <cstdlib>
int main(){
///BUT THIS DOES NOT WORK!
if ( (2 + 2) == (1 + 3) == (4 + 0) ){
std::cout << "not executed" << std::endl;
}
return EXIT_SUCCESS;
}
Let's say those numbers are actually variables. This is what I have to do:
#include <iostream>
#include <cstdlib>
int main(){
int n1 = 2;
int n2 = 2;
int n3 = 1;
int n4 = 3;
int n5 = 4;
int n6 = 0;
int a = n1 + n2;
///this works
if ( (n3 + n4) == a && (n5 + n6) == a){
std::cout << "executed!" << std::endl;
}
return EXIT_SUCCESS;
}
question: why does my first example not work?
I can assign multiple variables the same value like this:
#include <iostream>
#include <cstdlib>
int main(){
int a,b,c,d;
a=b=c=d=9;
///prints: 9999
std::cout <<a<<b<<c<<d<<'\n';
return EXIT_SUCCESS;
}
hoping someone can explain why this method of evaluating doesn't work.
It recently came to my attention while writing an if statement that determines if an nxn array is a magic square or not.
(2 + 2) == (1 + 3) == (4 + 0)
First, (2 + 2) == (1 + 3) evaluates to true, because it really holds that 4 == 4.
Then, you're comparing true == (4 + 0). In this case, boolean values are casted to integers:
true -> 1
false -> 0
Therefore you're comparing 1 == 4, what results in false.
This portion results in a boolean or integer, 0 or 1:
(2 + 2) == (1 + 3)
So the rest of the expression looks like:
1 == (4 + 0)
or
0 == (4 + 0)
Neither of these are correct.
The only operator that takes three arguments is the foo ? bar : baz operator. Everything else takes one or two arguments.
Related
void funct(int n)
{
int steps = 0;
if(n != 1){
steps++;
if((n % 2) == 0){
funct(n/2);
}
else if((n % 2) != 0){
funct((3*n + 1));
}
cout << steps << " ";
}
}
I tried this code, but it prints 1 in every time; I want my code to print how many times it has ben called.
steps is a local variable in funct each call to funct has its own copy. You need to pass a single variable through all calls to funct in order to count correctly.
void funct(int n, int& steps)
{
if(n != 1){
steps++;
if((n % 2) == 0){
funct(n/2, steps);
}
else if((n % 2) != 0){
funct((3*n + 1), steps);
}
}
}
int main()
{
int steps = 0;
funct(5, steps);
cout << steps << "\n";
}
As it stands, the steps variable in your function is a local variable of automatic storage duration. The latter means that it will be re-initialized to zero on each call of the function.
You can add the static keyword to the declaration to make it so that the initialization (to zero) happens only the first time the function is called (cppreference) and, from then on, the modified value will be maintained across subsequent calls of the function (until or unless it is explicitly reset1).
However, even with that, if you want to see a 'rolling' count, you will need to put the cout line (where the value is reported) before you make either of the recursive calls.
Here is a possibility (I have also changed your test condition from n != 1 to n > 1, in order to prevent the potential infinite recursion mentioned in the comments to your question):
void funct(int n)
{
static int steps = 0; // Initialized only the first time this line is reached
if (n > 1) {
steps++;
std::cout << steps << " ";
if ((n % 2) == 0) {
funct(n / 2);
}
else if ((n % 2) != 0) {
funct((3 * n + 1));
}
}
}
1 One way to implement this "explicit" reset would be to do so in an else block, when the recursion chain is complete. The following code shows how to do this, along with a short main that shows how the behaviour works on multiple, sequential 'top-level' calls to funct:
#include <iostream>
void funct(int n)
{
static int steps = 0;
if (steps == 0) {
std::cout << "Top-level call with " << n << "... ";
}
if (n > 1) {
steps++;
std::cout << steps << " ";
if ((n % 2) == 0) {
funct(n / 2);
}
else if ((n % 2) != 0) {
funct((3 * n + 1));
}
}
else {
std::cout << std::endl;
steps = 0;
}
}
int main()
{
funct(5);
funct(9);
funct(8);
return 0;
}
Output:
Top-level call with 5... 1 2 3 4 5
Top-level call with 9... 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Top-level call with 8... 1 2 3
Another way would be to use a 'special' value (like, for example, a negative number) to change the behaviour of the function so that, if such a value is passed, the function resets steps to zero and then returns immediately.
Let the function return how many times it has been called. And that is always one more than the number of calls that the recursive invocation reported:
int funct(int n)
{
int steps = 0;
if(n != 1){
if((n % 2) == 0){
steps = funct(n/2);
}
else {
steps = funct((3*n + 1));
}
}
return steps + 1;
}
int main()
{
int steps = funct(5);
cout << steps << "\n";
}
I want the result to be the returned value from the mystery function,but the result is always 0 .but I want the program to return a value that's collected from the mystery function
#include <iostream>
using namespace std;
int Mystery(int n)
{
// int k;
if (n <= 1)
{
return 0;
}
else
{
int k = n;
for (int i = 1; i <= n; i++)
{
k = k + 5;
}
cout << ((k * (n / 2)) + (8 * (n / 4)));
cout << "\n ";
return ((k * Mystery(n / 2)) + (8 * Mystery(n / 4)));
}
}
int main(void)
{
int i, n;
cout << "Enter n:"; //array size
cin >> n;
int result = Mystery(n);
cout << "The result is " << result;
return 0;
}
Let's desk check what happens when you call Mystery(2). The final return value is:
((k* Mystery(n/2)) + (8* Mystery(n/4)))
We know that n == 2 so let's substitute that:
((k* Mystery(1)) + (8* Mystery(0 /* by integer division of 2/4 */)))
This will call the function recursively twice with the respective arguments 1 and 0. But we know that the terminating case n <= 1 returns 0, so we can substitute that:
((k* 0) + (8* 0))
Anything multiplied by zero is zero, so this reduces to 0 + 0 which is also zero. It doesn't even matter what k is.
Quite simply, the terminating case for this recursion mandates that the result is always zero.
In the terminating case the return value is zero.
In the recursive case, the recursive call result is multiplied with another value to produce the return value.
Therefore, the result is always going to be zero for any n.
I'm not sure exactly how this function is supposed to work as you have not explained that, but changing the terminating case to return 1; may solve the problem.
I don't expect which result you want, but I think you can get write result when you correct conditions like
if (n == 0)
return 0;
if (n == 1)
return 1;
I hope it returns the right result.
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).
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));
I need a program in c++ that gets a number:
LOOP:
If that number is even divide it by 2 (n=n/2)
If it's not even you can do one of this operations:
n+1
n-1
LOOP ENDS
The program should do this until n=1.
But it should do this in the most efficient and fastest way and the only hint I have is that I can use DP approach.
And the output should be numbers of operations used to calculate that number.
For example:
15->16->8->4->2->1 output:5
35->36->18->9->8->4->2->1 output:7
here's the code I wrote but it's not completed yet and it's wrong since I couldn't figure out how should I add or subtract in each step:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
int n;
int h=0;
int i=0;
cout<<"Enter A Number:";
cin >> n;
int r=n;
int q=n;
cout<<r;
L1: while ( r % 2 == 0)
{
for(int m=0;r>1 && m==0 ;)
{ r=r / 2;h++;
m=r%2;
cout<<" => "<<r;
}}
while(r%2==1 && r>1)
{r=r-1;cout<<" => "<<r;h++;
goto L1;}
cout<<endl;
//**********************
cout<<q;
L2: while ( q % 2 == 0)
{
for(int m=0;q>1 && m==0 ;)
{ q=q / 2;i++;
m=q%2;
cout<<" => "<<q;
}}
while(q%2==1 && q>1)
{q=q+1;cout<<" => "<<q;i++;
goto L2;}
cout<<endl<<"First:"<<h<<endl<<"Second:"<<i<<endl;
system("pause");
}
If you want to solve it using DP:
I would state this: for each possible value 1 <=i < N find the optimal number of steps.
We use a priority queue to do this where we extract at each iteration the highest number. This is much more efficient than a vector of length N because a lot of states are unreachable (e.g. i=10 in the 15 example).
Consider that the starting state is (15,0): 15 with zero moves.
From this you create two new states (8,2) and (7,2) because for each you need two steps(add/subtract + division).
Extracting (8,2): (7,2)(4,3)
Extracting (7,2): (4,3)(3,4) Here comes DP! (7,2) would create the state (4,4) but you mantain in the queue only the minimum number of steps for the same state.
Extracting (4,3): (2,4)(3,4)
extracting(3,4): (2,4)(1,6)
Extracting (2,4): (1,5)
And that is it the solution is 5 steps.
Steps for 35:
(35,0) --- >(18,2) (17,2) -----> (17,2) (9,3) ----->
(9,3)(8,4) ----> (8,4)(5,5)(4,5) ----> (5,5)(4,5) ----->
(4,5)(3,7)(2,7)----> (3,7)(2,6) -----> (2,6)(1,9) ----> (1,7)
Solution: 7 steps.
Look if that helps you.
// Example program
#include <iostream>
#include <string>
int f (int n)
{
int iterations = 0;
while (n > 1)
{
if (n % 2 != 0)
{
std::cout << n << "->";
++n;
if (n & (n - 1))
n -= 2;
++iterations;
}
std::cout << n << "->";
n >>= 1;
++iterations;
}
std::cout << n << "->";
return iterations;
}
int main()
{
std::cout << f(15) << std::endl;
std::cout << f(41) << std::endl;
std::cout << f(43) << std::endl;
}
For use of dynamic programming, you should make recursion to get sub-solutions to the problem and then solve the problem itself. You also have to use a memory structure to hold the results of such sub-solutions.
#include <deque>
#include <iostream>
using namespace std;
int solve(deque<int>& solution, int number) {
if(number >= solution.size()) // resize to fit
solution.resize(number + 1, -1);
if(number == 1) // special case for number 1
return solution[number] = 0;
if(solution[number] != -1) // if already calculated
return solution[number];
if(number % 2 == 0) // n=n/2
return solution[number] = solve(solution, number/2) + 1;
int solutionA = solve(solution, number + 1); // n++
int solutionB = solve(solution, number - 1); // n--
return solution[number] = std::min(solutionA, solutionB) + 1; // best of n++,n--
}
int main() {
deque<int> solution;
cout << solve(solution, 35);
}
I'm not sure the code will work though.
Here's my recursive solution, verified up to 2097152 against the DP example.
The basis of it is using the value of the last two bits to determine the optimal operation. If the last bit is a 0, we always divide. If the last two bits are 11 we always increment as this transforms to 100 which enables two consecutive divide operations.
If the last two bits are 01 we decrement as this gives our next operation two consecutive divide operations vs incrementing which gives us 10.
The corner case is the number 3 where 3 -> 2 is desired over promotion to 4.
I suspect you can optimise this further by just scanning the bit pattern to determine the number of operations required. i.e. each zero requires a div op, and a set of ones can be changed into zeroes with a single addition.
#include <cstdint>
int solve_algorithmically(std::uint64_t number)
{
// If 1 there is nothing to do.
if (number <= 1)
return 0;
// Nasty hack to get around the case where number=3 & 3 == 3 will cause increment
if (number == 3)
return solve_algorithmically(number - 1) + 1;
// If we have an even number (0 in LSB)
if ((number & 1) == 0)
return solve_algorithmically(number / 2) + 1;
// If we have two consecutive 1's i.e. (...11) then increment as this wil give us two zeroes.
// The exception is the root case 3 where decrement wins.
if ((number & 3) == 3)
return solve_algorithmically(number + 1) + 1;
// The only other case ends last two bits = 01
return solve_algorithmically(number - 1) + 1;
}
int main() {
for (auto i = 1; i < 2097152; i++)
{
int alg = solve_algorithmically(i);
}
}