This code is copied from another user question and I`m curious how accumulate works here.
I get the correct result from this code, but would like to know what parameters lcm takes when in "accumulate". The init as A and the sum of the range as b? Please help
#include <numeric>
int gcd(int a, int b)
{
for (;;)
{
if (a == 0) return b;
b %= a;
if (b == 0) return a;
a %= b;
}
}
int lcm(int a, int b)
{
int temp = gcd(a, b);
return temp ? (a / temp * b) : 0;
}
int main()
{
int arr[] = { 5, 7, 9, 12 };
int result = std::accumulate(arr, arr + 4, 1, lcm);
std::cout << result << '\n';
}
The first argument that lcm will take is the accumulated value so far (which starts at 1, the third argument of std::accumulate), and the second argument will be an element in arr. Next, whatever lcm returns is passed as the first argument and the next element in arr as the second.
See a reference for more details.
You could easily write a and b to the standard output inside lcm to see what's happening.
Related
I want to make a program that takes 4 numbers eg.(a, b, c and d) and checks if using arithmetic operators i can make the first 3 numbers result to the fourth number, like if the input is (3, 4, 5, 23) this will check out true because
3 + 4 * 5 = 23,So i want to make an array that has the operators and use a loop to check every possible combination, Hope i made it clear.
Edit:
Its actually codeforces problem, given 4 numbers. Check whether he could get the fourth number by using the arithmetic operators (+,−,×) between the other three numbers. Knowing that an operator can be used only once. in this format ->(a□b□c=d).My question was if there is a way to make it automatic or do i have to code every possibility manually So sorry for any confusion i may have caused.
You can't store the operators in an array, but you could make wrapper functions for them and store those in an array.
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
int mul(int a, int b) {
return a * b;
}
int div(int a, int b) {
return a / b;
}
typedef int (*funptr)(int, int);
funptr arr[] = { add, sub, mul, div };
You can then call them like:
(arr[1])(2, 1) // call sub(2, 1)
The parentheses around arr[1] aren't needed in this case, but I like to put them for clarity.
No. You'd have to write a program to work this out. You could store something like function pointers to the arithmetic operators in an array, but I don't think that would help solve your problem. You'd still have to write the code to solve your problem.
Adding onto #CoffeeTableEspresso's answer, you can also put those function pointers into a map.
int add(int a, int b) {
return a + b;
}
int sub(int a, int b) {
return a - b;
}
int mul(int a, int b) {
return a * b;
}
int div(int a, int b) {
return a / b;
}
typedef int (*funptr)(int, int);
std::map<char,funptr> operators = {
{'+', add},
{'-', sub},
{'*', mul},
{'/', div}};
Then you can do
operators['+'](4,7);
Which might be a bit more readable, and you can iterate through these more easily.
I thought I would submit a compete answer. This works for positive numbers. It may take a bit more work to cover all the possibilities. And it does not answer to CoffeeTableEspresso's question about precedence. But it may help with your last question about if statements.
#include <iostream>
namespace {
auto add = [](int a, int b) {return a + b; };
auto sub = [](int a, int b) {return a - b; };
auto mult = [](int a, int b) {return a * b; };
auto divd = [](int a, int b) {return b ? a / b : -1; };
std::vector<int(*)(int, int)> ops = { add,sub,mult,divd };
}
int check(int* params)
{
for (size_t i = 0; i < 4; ++i)
for (size_t j = 0; j < 4; ++j)
{
auto result = ops[i](params[0], ops[j](params[1], params[2]));
if (params[3] == result)
return result;
else
std::cout << result << std::endl;
}
return -1;
}
int main()
{
int params[] = { 3, 4, 5, 23 };
std::cout << check(params);
}
Operators * / have a higher precedence than + -, so operator[i](A, operator[j](B, C)) solution doesn't really work.
You can write a little string calculator, and cycle through char-operators:
#include <iostream>
#include <sstream>
#include <vector>
#include <cmath>
double calculate(std::string str)
{
// calculator there
return -1;
};
int main()
{
std::vector<char> op = {'+', '-', '*', '/'};
std::vector<int> a = { 96, 3, 10, 42 };
for (auto op1: op)
for (auto op2: op)
{
std::stringstream ss;
ss << a[0] << op1 << a[1] << op2 << a[2];
double result = calculate( ss.str());
if (std::abs(a[3] - result) < 1E-6)
std::cout << ss.str() << " = " << a[3];
else
std::cout << ss.str() << " = " << result << " != " << a[3];
}
}
I need to count how many cubes of values between a and b (2 and 9 in this example) end with numbers between 2 and 5. Everything has to be done with recursion.
The output of this code is
part c = recc = 4
32767
0
It does not make sense to me. It calculates the value of n correctly, but then once asked to return it, returns either 0 or 32767, as if it was not defined.
Can anyone pinpoint the issue?
#include <iostream>
#include <string>
using namespace std;
void partb(int a, int b){
if(a<=b){
int p = (a*a*a)%10;
else if(p>=2 && p<=5){
cout<<a*a*a<<" ";
}
partb(a+1, b);
}
}
int recc(int n, int a, int b){
int p = (a*a*a)%10;
if(a>b){
cout<<"recc = " << n << endl;
return n;
}
else if(a<=b){
if(p>=2 && p<=5){
n++;
}
recc(n, a+1, b);
}
}
int partc(int a, int b){
int n = recc(0, a, b);
cout<<endl<< "part c = " << recc(0, a, b) << endl;
return n;
}
int main(){
int n=partc(2,9);
cout << n << endl;
return 0;
}
Not all control paths in your function return a value, so you were getting undefined behaviour when using the return value.
Now, this wasn't helped by the fact that the function itself is needlessly complicated. Let's rewrite it to use common practice for recursion:
int recc(int a, int b)
{
if (a > b) return 0;
int p = (a*a*a)%10;
int n = (p>=2 && p<=5) ? 1 : 0;
return n + recc(a+1, b);
}
Now your function is simpler. The recursion termination condition is right at the top. The function then decides whether a will contribute 1 or 0 to the count. And finally you return that value plus the count for a smaller range.
Notice how return n + recc(a+1, b); has broken the problem into a simple local solution combined with the recursive result of a reduced scope.
The invocation becomes simpler too, because you no longer have to pass in a redundant argument:
int partc(int a, int b)
{
int n = recc(a, b);
cout << endl << "part c = " << n << endl;
return n;
}
I'm pretty new to C++ and I have the following simple program:
int main()
{
int a = 5,b = 10;
int sum = a + b;
b = 6;
cout << sum; // outputs 15
return 0;
}
I receive always the output 15, although I've changed the value of b to 6.
Thanks in advance for your answers!
Execution of your code is linear from top to bottom.
You modify b after you initialize sum. This modification doesn't automatically alter previously executed code.
int sum = a + b; writes the result of adding a and b into the new variable sum. It doesn't make sum an expression that always equals the result of the addition.
There are already answers, but I feel that something is missing...
When you make an assignment like
sum = a + b;
then the values of a and b are used to calculate the sum. This is the reason why a later change of one of the values does not change the sum.
However, since C++11 there actually is a way to make your code behave the way you expect:
#include <iostream>
int main() {
int a = 5,b = 10;
auto sum = [&](){return a + b;};
b = 6;
std::cout << sum();
return 0;
}
This will print :
11
This line
auto sum = [&](){return a + b;};
declares a lambda. I cannot give a selfcontained explanation of lambdas here, but only some handwavy hints. After this line, when you write sum() then a and b are used to calculate the sum. Because a and b are captured by reference (thats the meaning of the &), sum() uses the current values of a and b and not the ones they had when you declared the lambda. So the code above is more or less equivalent to
int sum(int a, int b){ return a+b;}
int main() {
int a = 5,b = 10;
b = 6;
std::cout << sum(a,b);
return 0;
}
You updated the b value but not assigned to sum variable.
int main()
{
int a = 5,b = 10;
int sum = a + b;
b = 6;
sum = a + b;
cout << sum; // outputs 11
return 0;
}
I need to make a program that calculates the power of a given number using a recursive function. I wrote this I can't get it to work, once I get to the function itself it breaks. Any help? Thanks.
#include"stdafx.h"
#include<stdio.h>
#include<iostream>
using namespace std;
float power(float a, unsigned int b);
int main()
{
float a = 0;
unsigned int b = 0;
cout << "Insert base - ";
cin >> a;
cout << "Insert index - ";
cin >> b;
float result;
result = power(a, b);
cout << result;
return 0;
}
float power(float a, unsigned int b)
{
if (b <= 0)
{
return a;
}
return (a*power(a, b--));
}
Instead of b-- you need b-1 (or --b)
b-- reduces b by one, which has no effect because that instance of b is never used again. It passes the unreduced copy of b recursively.
Also, when b is zero, the result should be 1 rather than a
if ( b <= 0) return 1;
return a * power(a, --b);
But this question was asked so many times....
Recursion function to find power of number
Whenever we think about recursion, the first thing that comes to mind should be what the stopping criterion is. Next thing to consider is that we cannot have recursion without the use of a stack. Having said this, let us see at how we are able to implement this power function.
Stopping criteria
X ^ 0 = 1
Unwinding the stack
The base number may be raised to a positive or negative real number. Let us restrict our problem to just integers.
If A is the base and B the power, as a first step, take the absolute
value of B.
Secondly, store A in the stack and decrement B. Repeat
until B = 0 (stopping criterion). Store the result in the stack.
Thirdly, multiply all the A's stored by unwinding the stack.
Now the code
float power(float a, int b)
{
int bx = -b ? b < 0 : b;
if (bx == 0)
{
a = 1;
return a;
}
return 1/(a*power(a, --bx)) ? b < 0 : (a*power(a, --bx));
}
I have to input a number n, an a digit and a b digit and output the number n with all the a digits in it replaced by a b one. For example:
Input:
n = 1561525
a = 5
b = 9
Output:
n = 1961929
Should be recursive ! I didn't post any code as I've done it in a non-recursive way but apparently it's not even close to what I need.
Thanks for the help !
Check this, it works but maybe it is to much C
int convert(int num, int a, int b)
{
if( num )
{
int res = convert(num/10,a,b);
int t = num%10;
res *=10;
t = t == a ? b:t;
res = res + t;
return res;
}
return 0;
}
Divide by 10 the initial number, until nothing left of it, and then construct it again replacing a with b.
To make things easier, you can convert the number into a string (a char[] in C++). Then, it's a simple matter of iterating over it and checking at each step if the number we want to replace was found in the current position. For a possible solution, here's an implementation of the algorithm in Python - one of the nice things of the language is that it reads almost as pseudocode, and it should be relatively simple to port to C++:
def aux(n, a, b, i):
if i == len(n):
return ''
elif n[i] == a:
return b + aux(n, a, b, i+1)
else:
return n[i] + aux(n, a, b, i+1)
def change(n, a, b):
return int(aux(str(n), str(a), str(b), 0))
It works as expected:
change(1561525, 5, 9)
=> 1961929
So the easiest and safest way I can think of, is by using std::replace:
int replace(int num, int d1, int d2) {
string s = std::to_string(num); // convert to string
std::replace( s.begin(), s.end(), d1+'0', d2+'0'); // call std::replace
return atoi( s.c_str() ); // return the int
}
Now if you really have to use recursion (there is no need for it here), here's one possible solution:
using std::string;
// recursive function, accepts a string, current index, c2 replaces c1
string replace_rec (string s, unsigned index, char c1, char c2) {
// check if the it's still a valid index
if (index < s.size()) {
// if this is a char to be converted, do so
if (s[index] == c1)
s[index] = c2;
// call itself but with an updated string and incremented index
replace_rec(s, index+1, c1, c2);
}
// the last call will result in the string with all chars checked. return it
return s;
}
// call this function with input, the num to be replaced and what with
int replace(int num, int d1, int d2) {
string s = std::to_string(num); // convert to string
// convert the result back to int and return it.
return atoi( replace_rec(s, 0, d1+'0', d2+'0').c_str() );
}
In any case, you can call your replace() function like this:
int main(){
cout << replace (4578, 4, 9); // output: 9578
cin.get();
}