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));
}
Related
Here is the problem I must do(Just for context): Write a program that will input 2 integers from the user, will then calculate the first to the power of the second and then output the result. The Input, calculation and output should be in three separate subprograms/functions. You must calculate the exponentiation using a WHILE loop and multiplying the first number, the required number of times. For this homework only, you are allowed to use global variables to move information between functions.
Here is my code:
#include <iostream>
#include <cmath>
using namespace std;
double a, b, ans;
int main()
{
cout << "Please enter two whole numbers: ";
cin >> a >> b;
cout << conclusion() << calc();
system("pause");
return 0;
}
int calc()
{
double ans = pow(a, b);
return 0;
}
int conclusion()
{
cout << a << " To the power of " << b
<< " is " << ans;
return 0;
}
So here's what I'm having an issue with, I do online classes. The dude is like, "here's a problem, figure it out and just do it." Which is fine I guess, but when things like this come up its hard to find certain tutorials and questions. Anyway, I got my BASE code down. Now I need a while loop, and have no idea what this means: calculate the exponentiation using a WHILE loop and multiplying the first number, the required number of times.
I figured I could just do a while and do
double ans = pow(a, b);
But that's not the case apparently. That's what my chapter taught me, but not with a while and all this extra stuff you need to do for this. I asked a classmate, she said she had a really difficult time as well, and her example to me was:
int a = 0;
int b = 0;
int c = 1;
cin >> a;
cin >> b;
int powerOp(int a, int b, int c)
{
while (b > 0)
{
c = c * a;
b--;
}
cout << c;
return c;
}
I have been working almost all day and can't figure this out. I don't understand why we need to factorize and set the int = 1. I thought it could simply be
double ans = pow(a, b); //a and b being the 2 numbers the user inputs
Its pretty simple, lets say you have 2^3. You and I both agree that it is the same as doing 2x2x2. You mutiplied you first number A by itself B (your second number) times. Now for your loop, what you want have your second number server as your counter AND loop exit condition. Something like this
double YourPowerFunction(int a, int b)
{
int counter = 0;
double result = 1;
while (counter < b)
{
counter++:
result = result * a;
}
return result;
}
Okay so I'm pretty sure I found the answer. Result is the variable for ans
int calc() //function for calculation
{
//Still not sure how I did this one, after hours of playing around with it
while (b > 0) //This code is adding a 0 in the result. I can't figure it out
{
result = result * a;
b--;
}
return (result);
}
This is just a simple solution, as it wants to add a 0 in the end result.
I made a program for codechef and its wrong apparantly (although all tests have been positive). The code is:
#include <iostream>
using namespace std;
int g (int a,int b){
return b == 0 ? a : g(b, a % b);
}
int l (int a, int b){
return (a*b)/(g(a,b));
}
int main() {
int n;
cin >> n;
int a[n],b[n];
for (int x = 0;x<n;x++){
cin >> a[x] >> b[x];
}
for (int x = 0;x<n;x++){
cout << g(a[x],b[x]) << " "<< l(a[x],b[x]) << endl;
}
return 0;
}
Codechef won't tell me what integers dont work, and im pretty sure my gcd function is legit.
Since gcd is properly defined as the largest non-negative common divisor, you can save yourself the annoying details of signed division, e.g.,
static unsigned gcd (unsigned a, unsigned b)
{
/* additional iteration if (a < b) : */
for (unsigned t = 0; (t = b) != 0; a = t)
b = a % b;
return a;
}
Likewise for lcm; but the problem here is that (a*b) may overflow. So if you have two large (signed) int values that are co-prime, say: 2147483647 and 2147483629, then gcd(a,b) == 1, and (a*b)/g overflows.
A reasonable assumption on most platforms is that unsigned long long is twice the width of unsigned - although strictly speaking, it doesn't have to be. This is also a good reason to use exact types like [u]int32_t and [u]int64_t.
One thing you can be sure of is that a/g or b/g will not cause any issues. So a possible implementation might be:
static unsigned long long lcm (unsigned a, unsigned b)
{
return ((unsigned long long) a) * (b / gcd(a, b)));
}
If your test values are 'positive' (which is what I think you mean), you can cast them prior to (unsigned) prior to call. Better yet - replace all your int variables with unsigned int (though the loop variables are fine), and save yourself the trouble to begin with.
#include <iostream>
using namespace std;
double calc(int a, int b);
int main()
{
int n1, n2;
cout << "Enter a number for a: ";
cin >> n1;
cout << "Enter a number for b: ";
cin >> n2;
cout << calc(n1, n2) << endl;
system("PAUSE");
return 0;
}
double calc(int a, int b)
{
double s;
s = (a) / ((sqrt(a / b)));
return s;
}
This program is meant to check whether the two integers are greater than zero. If it is it will calcualte the formula. Otherwise if one of the integers is zero or less than zero it will not return anything and exit the program.
My question here is that no matter what I input for a and b, i keep getting 1.#INF as the output and I have no idea why. I've checked the formula in a seperate program and it worked fine.
Any ideas?
Here, you are operating with int numbers:
s = (a) / ((sqrt(a / b)));
If a is less then b, then a/b (both are integers, remember, so the fractional part of the result will simply be lost) will be equal to 0, which leads to division by 0. You need to cast one of the numbers to double:
s = (a) / ((sqrt(static_cast<double>(a) / b)));
sqrt takes and returns a double. When you call it with integer arguments it will be converted in a double, and will thus get the value of infinity.
change your function signature to:
double calc(double a, double b);
and declare n1 and n2 as double.
You say that the function will exit the program when one of the integers are 0 or less, but where?
Try to check them like this:
Additionally, you should have a check whether a is greater than b
double calc(int a, int b)
{
double s;
if(a <= 0) exit(-1);
if(b <= 0) exit(-1);
if(a < b) exit(-1);
s = (a) / ((sqrt(a / b)));
return s;
}
You are having problems with infinity. For it use isinf. Here is some sample usage:
#include <stdio.h> /* printf */
#include <math.h> /* isinf, sqrt */
int main()
{
printf ("isinf(-1.0/0.0) : %d\n",isinf(-1.0/0.0));
printf ("isinf(sqrt(-1.0)): %d\n",isinf(sqrt(-1.0)));
return 0;
}
output:
isinf(-1.0/0.0) : 1 isinf(sqrt(-1.0): 0
My code works when the values are small e.g. [a = 1, gos = 0.5, N = 1] & [a = 1, gos = 0.2 , N = 2].
However, it crashes when bigger values are entered. e.g.[a = 10, gos = 0.01, N = 18] & [a=50, gos=0.01, N=64].
How can I fix it?
Here's the code:
#include <cstdlib>
#include <iostream>
using namespace std;
double num_trunks(double A, double B, int N);
double num_trunk_checker(double B, double gos, int N, double A);
double num_trunks(double A, double B, int N)
{
double gos_prev = 1;
double gos;
int k = 1;
while (k != (N+1))
{
gos = (A*gos_prev)/(k+(gos_prev)*A);
gos_prev = gos;
k++;
};
num_trunk_checker(B,gos,N,A);
}
double num_trunk_checker(double B, double gos, int N, double A)
{
if (B != gos)
{
N = N + 1;
num_trunks(A,B,N);
}
else
{
cout << "Number of trunks: " << N << "\n";
}
}
int main(int argc, char *argv[])
{
double A, gos;
int N = 1;
cout << "A: ";
cin >> A;
cout << "gos: ";
cin >> gos;
num_trunks(A,gos,N);
system("PAUSE");
return EXIT_SUCCESS;
}
In num_trunks(A, B, N), you calculate a gos value, and then call num_trunk_checker(B, gos, N, A). But in num_trunk_checker, if B does not match gos, you turn around and call num_trunks(A, B, N+1). So the only thing that changed is a larger N, and you get infinite recursion if gos never equals B.
num_trunks(A, B, N)
calculuate gos (which has to be less than 1)
num_trunk_checker(B, gos, N, A)
num_trunk_checker(B, gos, N, A)
if (B != gos) num_trunks(A, B, N+1)
It is possible for gos to step over the value of B, so you never get equality.
Perhaps what you meant was:
if (gos > B) //...
you should read the FAQ about floating point comparisons
http://www.parashift.com/c++-faq/floating-point-arith.html
then try sth like
if (fabs(B-gos)<1.e-6)
in num_trunk_checker function
Without more information (what crashes? How long does it take?) it is impossible to solve your problem perfectly. But some reasonable guesses can be made.
Floating point comparisons are not completely accurate and are usually done by subtracting the two values and comparing against a small value (called epsilon). It might be better, when checking (B != gos), to do something like (B - gos < .00001). Without this, the computation may not terminate; and if it did not, the recursion would continue indefinitely, until the stack overflowed and the program crashed.
Another possibility (I am not running the program to see what happens myself) is that with larger values, the multiplication causes them to overflow (to exceed the maximum possible value that can be represented in a double), causing an exception to be thrown.
I know that we can use the logic of binary adder where Sum = a XOR b and Carry = a AND b
I have also got a solution:
int add(int a, int b)
{
if(b == 0)
return sum;
sum = a ^ b;
carry = (a & b) << 1;
return add(sum,carry);
}
What I don't understand here is why is the carry bit shifted, or multiplied by 2 during each recursion?
I find this a bit tricky to explain, but here's an attempt; think bit by bit addition, there are only 4 cases;
0+0=0
0+1=1
1+0=1
1+1=0 (and generates carry)
The two lines handle different cases
sum = a ^ b
Handles case 0+1 and 1+0, sum will contain the simple case, all bit positions that add up to 1.
carry = (a & b) << 1
The (a & b) part finds all bit positions with the case 1+1. Since the addition results in 0, it's the carry that's important, and it's shifted to the next position to the left (<<1). The carry needs to be added to that position, so the algorithm runs again.
The algorithm repeats until there are no more carries, in which case sum will contain the correct result.
Btw, return sum should be return a, then both sum and carry could be regular local variables.
public class AddSub {
int sum=0,carry=0;
public static void main(String[] args) {
System.out.println("Add "+new AddSub().addition(93,5));
System.out.println("Sub "+new AddSub().subtraction(7,60));
System.out.println("Sub "+new AddSub().multiplication(9,60));
}
public int addition(int a, int b)
{
if(b==0)
{
return a;
}
else
{
sum = a^b;
carry = (a&b)<<1;
return addition(sum,carry);
}
}
public int subtraction(int a, int b){
return addition(a,addition(~b,1));
}
public int multiplication(int a, int b){
for(int i=0;i<b/2;i++)
sum = addition(sum,addition(a,a));
return sum;
}
}
Hi don't be think yourself too difficult.
Here the simple way to do that.
Consider a=5, b=10;
c=a-(-b);
c=15;
that is it.