Im trying to make a function that does division with out the / symbol
long q(int nm1, int nm2)
{
long q = 0;
while ( num1 > num2)
{
some subtraction here
}
return q;
}
the idea is to assume the input is in order and the first is to be divided by the second.
This means subtract the second from the first until the second is less then the first number.
I tried many different ways to do this but for what ever reason I cant hit it.
For now I am assuming the number is positive and wont return division by zero (I can fix that later by calling my other functions)
This means subtract the the second from the first until the second is less than the first number.
And what's the problem with that?
int div(int num, int den)
{
int frac;
for (frac = 0; num >= den; num -= den, frac++)
;
return frac;
}
What you're original post is trying to do is the Division by repeated subtraction algorithm. Have a look at Wikipedia:
The simplest division algorithm, historically incorporated into a
greatest common divisor algorithm presented in Euclid's Elements, Book
VII, Proposition 1, finds the remainder given two positive integers
using only subtractions and comparisons
while N ≥ D do
N := N - D
end
return N
Just add a counter in your while loop to keep track of the number of iterations (which is what you will want to return) and after your loop N will contain your remainder (if it is not 0 of course).
This code will work only if the num and den are integer values.
int main( int num, int den )
{
if(den==0)
{
return 1;
}
else
{
while(num!=0)
{
num = num - den;
}
}
return 0;
}
Just improving the above answer slightly.
Use modulus
long div(int num, int den)
{
int frac;
int num2 = num;
for (frac = 0; num2 >= den; num2 -= den, frac++)
;
// i needed the original num and den.
return ( (long) frac )+( num % den );
// casts frac to long then adds the modulus remainder of the values.
}
just a bit optimization: you don't want to have linear time complexity with the input value
int div(int num, int den)
{
int result = 0;
int i;
long long x;
long long y;
if (num < 0) return -div(-num, den);
if (den < 0) return -div(num, den);
if (num < den) return 0;
x = num;
y = den;
i = 0;
while((i < 32) && (x > (y << (i+1)))) i++;
for(;i>0; i++)
{
if (x > (y << i))
{
x -= y;
result += 1 << i;
}
}
return result;
}
Related
I'm trying to translate this series into a code that give me the sum of it. Here is the series:
X + (-1/3)X^3 + (1/5)X^5 + (-1/7)X^7 + …. +((-1)^(n-1)/2n-1)X^(2n-1)
That's the code (by the way I can't use cmath library..):
#include <iostream>
using namespace std;
int main()
{
cout << "enter 2 numbers: \n";
int x, n;
cin >> x;
do
{
cin >> n;
if (n <= 0) cout << "ERROR \n";
} while (n <= 0);
int i{ 1 }; // index for the first organ and so on.
double denom{ 2.0 * i - 1 }; // the denominator and the power in the equation.
bool posCardinal{ 1 }; // check if the cardinal is positive.
int cardinal{ 1 };
if (posCardinal) cardinal = 1;
else cardinal = -1;
double factor{ cardinal / denom }; // the factor.
int xValue{ x }; // the value of X each time.
double an{ factor * xValue }; // general organ.
double sum{ 0 }; // the total sum.
for (i = 1; i <= n; ++i)
{
factor = cardinal / denom;
for (int j{ 1 }; j < denom && i != 1; ++j)
{
xValue *= x;
}
an = factor * xValue;
sum += an;
xValue = x;
!posCardinal;
}
cout << sum;
}
Why doesn't the code show me the sum?
Thank you all very much!!
As you are working with fractions in the series, you should think about using float or double (depending on what precision do you need) for your x, xValue, sum, an and factor (as its value is 1/some_int, so if factor is int, then the value will almost always be 0).
Your second problem are both for nested loops, which do not have any incrementer, so they work endlessly, similarly to while (true){...} loop - almost always i is smaller than denom (only if i=1 the value of denom is 1). You should think about rebuilding these functions to work on some other variable, let's say j. Then you could count n-th power of x this way:
for (int j = 0; j < denom; j++)
xValue *= xValue;
There are still few things you should fix, e.g your denom does not change its value when the program is running, it has fixed value after you first declare it after i.
I wrote a simple C++ program that computes permutations/factorials in 2 different methods. The problem arises when I try to use the longer method (p1) with 20 and 2. Granted, "20!" is a HUGE number. Is there a limit with integers when calculating the factorial using the recursion method?
#include <iostream>
using namespace std;
int p1(int n, int r);
int p2(int n, int r);
int factorial(int x);
int main()
{
cout << p1(10, 8) << endl;
cout << p2(10, 8) << endl;
cout << p1(4, 3) << endl;
cout << p2(4, 3) << endl;
cout << p1(20, 2) << endl; // THE NUMBER PRINTS INCORRECTLY HERE
cout << p2(20, 2) << endl;
system("PAUSE");
return EXIT_SUCCESS;
}
int p1(int n, int r) // long version, recursively calls factorial
{
return (factorial(n) / factorial(n - r));
}
int factorial(int x)
{
if (x == 0)
return 1;
else if (x > 0)
return (x * factorial(x - 1));
}
int p2(int n, int r) // shortcut, does arithmetic in for loop
{
int answer = n;
for (int i = 1; i < r; i++)
{
answer *= n - 1;
n--;
}
return answer;
}
20! is 2.4*10^18
You can check out a reference of limits.h to see what the limits are.
consider that 2^32 is 4.2*10^9. long int is usually a 32-bit value.
consider that 2^64 is 1.8*10^19, so a 64-bit integer will get you through 20! but no more. unsigned long long int should do it for you then.
unsigned long long int p1(int n, int r)
{
return (factorial(n) / factorial(n - r));
}
unsigned long long int factorial(unsigned long long int x)
{
if (x == 0)
return 1;
else if (x > 0)
return (x * factorial(x - 1));
}
unsigned long long int p2(int n, int r)
{
unsigned long long int answer = n;
for (int i = 1; i < r; i++)
{
answer *= n - 1;
n--;
}
return answer;
}
If you are allowed in this assignment, consider using float or double, unless you need absolute precision, or just need to get to 20 and be done. If you do need absolute precision and to perform a factorial above 20, you will have to devise a way to store a larger integer in a byte array like #z32a7ul states.
Also you can save an operation by doing answer *= --n; to pre-decrement n before you use it.
20! exceeds the integer range. Your shortcut function doesn't exceed simply because you don't calculate the whole faculty, but 20*19
If you really need it, you may create a class that holds a variable-length array of bytes, and define operators on it. In that case, only the available memory and your patiance will limit the size of numbers. I think Scheme (a LISP dialect) does something like that.
P = (10^9 + 7)
Choose(m, n) = m! / (n! * (m - n)!)
I want to calculate the value of Choose(m, n) mod P for large m and n.
How can I do that in C++ ?
This is what I use as it has a fairly good range without too much intermediate overflow. However C(n,k) gets big fast, it is O(n^k) after all.
size_t N_choose_K(size_t n, size_t k)
{
size_t numer = 1;
size_t denom = 1;
if (k > n - k) {
k = n - k;
}
while (k > 0) {
numer *= n;
denom *= k;
--n; --k;
}
return numer / denom;
}
EDIT: Assumes you need integral results. You can move to floating point results and get more range if you need it and can stand to lose the accuracy.
You can use the fact that multiplication is closed under Zp meaning that: a b mod p = (a mod p) (b mod p) mod p. Using this theorem, one can calculate ab mod p effectively (for instance, this Python implementation.
Next we can make use of Euler's theorem saying: a-1 mod p=a(p-2) mod p.
Now that we know these facts, we can come up with an effective solution: first we multiply over all elements in the numerator, this is thus a range from k+1 (inclusive) to n, and since this is a multiplication, we can always perform a modulo:
long long numerator(int n, int k, int p) {
long long l = 1;
for(int j = k+1; j <= n; j++) {
l = (l*j)%p;
}
return l;
}
Now we still need to divide it by (n-k)!. We can do this by first calculating (n-k)! mod p like we already did in the previous code fragment:
long long denominator(int n, int k, int p) {
long l = 1;
for(int j = 2; j <= n-k; j++) {
l = (l*j)%p;
}
return l;
}
Now in order to divide it, we can use Euler's theorem on the result of denominator. Therefore we first implement the pow function with modulo:
long long pow(long long a, int k, int p) {
if(k == 0) {
return 1;
}
long long r = pow((a*a)%p,k>>0x01,p);
if((k&0x01) == 0x01) {//odd number
r = (r*a)%p;
}
return r;
}
Now we can merge these together like:
long long N_choose_K(int n, int k, int p) {
long long num = numerator(n,k,p);
long long den = denominator(n,k,p);
return (num*pow(den,p-2,p))%p;
}
So what you basically do is you determine the numerator num in Zp, the value of the denominator den in Zp, and then you use Euler's theorem to find the inverse of the denominator in Zp, such that you can multiply and perform the last modulo operation. Then you can return it.
I'm writing a recursion function to find the power of a number and it seems to be compiling but doesn't output anything.
#include <iostream>
using namespace std;
int stepem(int n, int k);
int main()
{
int x, y;
cin >> x >> y;
cout << stepem(x, y) << endl;
return 0;
}
int stepem(int n, int k)
{
if (n == 0)
return 1;
else if (n == 1)
return 1;
else
return n * stepem(n, k-1);
}
I tried debugging it, and it says the problem is on this line :
return n * stepem(n, k-1);
k seems to be getting some weird values, but I can't figure out why?
You should be checking the exponent k, not the number itself which never changes.
int rPow(int n, int k) {
if (k <= 0) return 1;
return n * rPow(n, --k);
}
Your k is getting weird values because you will keep computing until you run out of memory basically, you will create many stack frames with k going to "-infinity" (hypothetically).
That said, it is theoretically possible for the compiler to give you a warning that it will never terminate - in this particular scenario. However, it is naturally impossible to solve this in general (look up the Halting problem).
Your algorithm is wrong:
int stepem(int n, int k)
{
if (k == 0) // should be k, not n!
return 1;
else if (k == 1) // this condition is wrong
return 1;
else
return n * stepem(n, k-1);
}
If you call it with stepem(2, 3) (for example), you'll get 2 * 2 * 1 instead of 2 * 2 * 2 * 1. You don't need the else-if condition:
int stepem(int n, unsigned int k) // unless you want to deal with floating point numbers, make your power unsigned
{
if (k == 0)
return 1;
return n * stepem(n, k-1);
}
Didn't test it but I guess it should give you what you want and it is tail recursive.
int stepemi(int result, int i int k) {
if (k == 0 && result == i)
return 1;
else if (k == 0)
return result;
else
return stepem(result * i, i, k-1);
}
int stepem(int n, int k) {
return stepemi(n, n, k);
}
The big difference between this piece of code and the other example is that my version could get optimized for tail recursive calls. It means that when you call stepemi recursively, it doesn't have to keep anything in memory. As you can see, it could replace the variable in the current stack frame without having to create a new one. No variable as to remain in memory to compute the next recursion.
If you can have optimized tail recursive calls, it also means that the function will used a fixed amount of memory. It will never need more than 3 ints.
On the other hand, the code you wrote at first creates a tree of stackframe waiting to return. Each recursion will add up to the next one.
Well, just to post an answer according to my comment (seems I missed adding a comment and not a response :-D). I think, mainly, you have two errors: you're checking n instead of k and you're returning 1 when power is 1, instead of returning n. I think that stepem function should look like:
Edit: Updated to support negative exponents by #ZacHowland suggestion
float stepem(int n, int k)
{
if (k == 0)
return 1;
else
return (k<0) ?((float) 1/n) * stepem(n, k+1) :n * stepem(n, k-1);
}
// Power.cpp : Defines the entry point for the console application.
//
#include <stream>
using namespace std;
int power(int n, int k);
void main()
{
int x,y;
cin >>x>>y;
cout<<power(x,y)<<endl;
}
int power(int n, int k)
{
if (k==0)
return 1;
else if(k==1) // This condition is working :) //
return n;
else
return n*power(n,k-1);
}
your Program is wrong and it Does not support negative value given by user,
check this one
int power(int n, int k){
'if(k==0)
return 1;
else if(k<0)
return ((x*power(x,y+1))*(-1));
else
return n*power(n,k-1);
}
sorry i changed your variable names
but i hope you will understand;
#include <iostream>
using namespace std;
double power(double , int);// it should be double because you also need to handle negative powers which may cause fractions
int main()
{
cout<<"please enter the number to be powered up\n";
double number;
cin>>number;
cout<<"please enter the number to be powered up\n";
int pow;
cin>>pow;
double result = power(number, pow);
cout<<"answer is "<<result <<endl;
}
double power( double x, int n)
{
if (n==0)
return 1;
if (n>=1)
/*this will work OK even when n==1 no need to put additional condition as n==1
according to calculation it will show x as previous condition will force it to be x;
try to make pseudo code on your note book you will understand what i really mean*/
if (n<0)
return x*power(x, n-1);
return 1/x*power(x, n+1);// this will handle negative power as you should know how negative powers are handled in maths
}
int stepem(int n, int k)
{
if (k == 0) //not n cause you have to vary y i.e k if you want to find x^y
return 1;
else if (k == 1)
return n; //x^1=x,so when k=1 it should be x i.e n
else
return n * stepem(n, k-1);
}
I was finding out the algorithm for finding out the square root without using sqrt function and then tried to put into programming. I end up with this working code in C++
#include <iostream>
using namespace std;
double SqrtNumber(double num)
{
double lower_bound=0;
double upper_bound=num;
double temp=0; /* ek edited this line */
int nCount = 50;
while(nCount != 0)
{
temp=(lower_bound+upper_bound)/2;
if(temp*temp==num)
{
return temp;
}
else if(temp*temp > num)
{
upper_bound = temp;
}
else
{
lower_bound = temp;
}
nCount--;
}
return temp;
}
int main()
{
double num;
cout<<"Enter the number\n";
cin>>num;
if(num < 0)
{
cout<<"Error: Negative number!";
return 0;
}
cout<<"Square roots are: +"<<sqrtnum(num) and <<" and -"<<sqrtnum(num);
return 0;
}
Now the problem is initializing the number of iterations nCount in the declaratione ( here it is 50). For example to find out square root of 36 it takes 22 iterations, so no problem whereas finding the square root of 15625 takes more than 50 iterations, So it would return the value of temp after 50 iterations. Please give a solution for this.
There is a better algorithm, which needs at most 6 iterations to converge to maximum precision for double numbers:
#include <math.h>
double sqrt(double x) {
if (x <= 0)
return 0; // if negative number throw an exception?
int exp = 0;
x = frexp(x, &exp); // extract binary exponent from x
if (exp & 1) { // we want exponent to be even
exp--;
x *= 2;
}
double y = (1+x)/2; // first approximation
double z = 0;
while (y != z) { // yes, we CAN compare doubles here!
z = y;
y = (y + x/y) / 2;
}
return ldexp(y, exp/2); // multiply answer by 2^(exp/2)
}
Algorithm starts with 1 as first approximation for square root value.
Then, on each step, it improves next approximation by taking average between current value y and x/y. If y = sqrt(x), it will be the same. If y > sqrt(x), then x/y < sqrt(x) by about the same amount. In other words, it will converge very fast.
UPDATE: To speed up convergence on very large or very small numbers, changed sqrt() function to extract binary exponent and compute square root from number in [1, 4) range. It now needs frexp() from <math.h> to get binary exponent, but it is possible to get this exponent by extracting bits from IEEE-754 number format without using frexp().
Why not try to use the Babylonian method for finding a square root.
Here is my code for it:
double sqrt(double number)
{
double error = 0.00001; //define the precision of your result
double s = number;
while ((s - number / s) > error) //loop until precision satisfied
{
s = (s + number / s) / 2;
}
return s;
}
Good luck!
Remove your nCount altogether (as there are some roots that this algorithm will take many iterations for).
double SqrtNumber(double num)
{
double lower_bound=0;
double upper_bound=num;
double temp=0;
while(fabs(num - (temp * temp)) > SOME_SMALL_VALUE)
{
temp = (lower_bound+upper_bound)/2;
if (temp*temp >= num)
{
upper_bound = temp;
}
else
{
lower_bound = temp;
}
}
return temp;
}
As I found this question is old and have many answers but I have an answer which is simple and working great..
#define EPSILON 0.0000001 // least minimum value for comparison
double SquareRoot(double _val) {
double low = 0;
double high = _val;
double mid = 0;
while (high - low > EPSILON) {
mid = low + (high - low) / 2; // finding mid value
if (mid*mid > _val) {
high = mid;
} else {
low = mid;
}
}
return mid;
}
I hope it will be helpful for future users.
if you need to find square root without using sqrt(),use root=pow(x,0.5).
Where x is value whose square root you need to find.
//long division method.
#include<iostream>
using namespace std;
int main() {
int n, i = 1, divisor, dividend, j = 1, digit;
cin >> n;
while (i * i < n) {
i = i + 1;
}
i = i - 1;
cout << i << '.';
divisor = 2 * i;
dividend = n - (i * i );
while( j <= 5) {
dividend = dividend * 100;
digit = 0;
while ((divisor * 10 + digit) * digit < dividend) {
digit = digit + 1;
}
digit = digit - 1;
cout << digit;
dividend = dividend - ((divisor * 10 + digit) * digit);
divisor = divisor * 10 + 2*digit;
j = j + 1;
}
cout << endl;
return 0;
}
Here is a very simple but unsafe approach to find the square-root of a number.
Unsafe because it only works by natural numbers, where you know that the base respectively the exponent are natural numbers. I had to use it for a task where i was neither allowed to use the #include<cmath> -library, nor i was allowed to use pointers.
potency = base ^ exponent
// FUNCTION: square-root
int sqrt(int x)
{
int quotient = 0;
int i = 0;
bool resultfound = false;
while (resultfound == false) {
if (i*i == x) {
quotient = i;
resultfound = true;
}
i++;
}
return quotient;
}
This a very simple recursive approach.
double mySqrt(double v, double test) {
if (abs(test * test - v) < 0.0001) {
return test;
}
double highOrLow = v / test;
return mySqrt(v, (test + highOrLow) / 2.0);
}
double mySqrt(double v) {
return mySqrt(v, v/2.0);
}
Here is a very awesome code to find sqrt and even faster than original sqrt function.
float InvSqrt (float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f375a86 - (i>>1);
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
x = x*(1.5f - xhalf*x*x);
x = x*(1.5f - xhalf*x*x);
x=1/x;
return x;
}
After looking at the previous responses, I hope this will help resolve any ambiguities. In case the similarities in the previous solutions and my solution are illusive, or this method of solving for roots is unclear, I've also made a graph which can be found here.
This is a working root function capable of solving for any nth-root
(default is square root for the sake of this question)
#include <cmath>
// for "pow" function
double sqrt(double A, double root = 2) {
const double e = 2.71828182846;
return pow(e,(pow(10.0,9.0)/root)*(1.0-(pow(A,-pow(10.0,-9.0)))));
}
Explanation:
click here for graph
This works via Taylor series, logarithmic properties, and a bit of algebra.
Take, for example:
log A = N
x
*Note: for square-root, N = 2; for any other root you only need to change the one variable, N.
1) Change the base, convert the base 'x' log function to natural log,
log A => ln(A)/ln(x) = N
x
2) Rearrange to isolate ln(x), and eventually just 'x',
ln(A)/N = ln(x)
3) Set both sides as exponents of 'e',
e^(ln(A)/N) = e^(ln(x)) >~{ e^ln(x) == x }~> e^(ln(A)/N) = x
4) Taylor series represents "ln" as an infinite series,
ln(x) = (k=1)Sigma: (1/k)(-1^(k+1))(k-1)^n
<~~~ expanded ~~~>
[(x-1)] - [(1/2)(x-1)^2] + [(1/3)(x-1)^3] - [(1/4)(x-1)^4] + . . .
*Note: Continue the series for increased accuracy. For brevity, 10^9 is used in my function which expresses the series convergence for the natural log with about 7 digits, or the 10-millionths place, for precision,
ln(x) = 10^9(1-x^(-10^(-9)))
5) Now, just plug in this equation for natural log into the simplified equation obtained in step 3.
e^[((10^9)/N)(1-A^(-10^-9)] = nth-root of (A)
6) This implementation might seem like overkill; however, its purpose is to demonstrate how you can solve for roots without having to guess and check. Also, it would enable you to replace the pow function from the cmath library with your own pow function:
double power(double base, double exponent) {
if (exponent == 0) return 1;
int wholeInt = (int)exponent;
double decimal = exponent - (double)wholeInt;
if (decimal) {
int powerInv = 1/decimal;
if (!wholeInt) return root(base,powerInv);
else return power(root(base,powerInv),wholeInt,true);
}
return power(base, exponent, true);
}
double power(double base, int exponent, bool flag) {
if (exponent < 0) return 1/power(base,-exponent,true);
if (exponent > 0) return base * power(base,exponent-1,true);
else return 1;
}
int root(int A, int root) {
return power(E,(1000000000000/root)*(1-(power(A,-0.000000000001))));
}