The division algorithm states that given two integers a and d, with d ≠ 0, there exists unique integers q and r such that a = qd + r and 0 ≤ r < |d|, where |d| denotes the absolute value of d. The integer q is the quotient, r is the remainder, d is the divisor, and a is the dividend. prompt the user for a dividend and divisor and then display the division algorithm's results:
If a = 17 and d = 3, then q = 5 and r = 2, since 17 = 5 * 3 + 2.
If a = 17 and d = -3, then q = -5 and r = 2, since 17 = -5 * -3 + 2.
The C++ operators for integer division do not conform to the division algorithm. Explain in output displayed to the user of the program when to expect results that disagree with the division algorithm. The program should not attempt to resolve this issue.
Ok, so I've been trying to figure this out for a few days now and I just can't crack it. The only way I can think of solving this is by using mod to find r or using a successive subtraction to find q. However, I'm pretty sure both of those solution don't really count. Is there some other way to solve this problem?
[Edit] I don't think successive subtraction works because that's just Euclid's algorithm so I really wouldn't be using this algorithm and using modulus would just like using the C++ division operator.
Here's a hint. For positive numbers, everything works out ok.
The C++ expression q = 17/3 results in q == 5.
But for negative numbers:
The expression q = -17/3 results in q == -5
With the way the question is worded, I'm pretty sure you are supposed to use mod to find r and the division operator to find q. It says straight up "The C++ operators for integer division do not conform to the division algorithm. Explain in output displayed to the user of the program when to expect results that disagree with the division algorithm. The program should not attempt to resolve this issue." This means, don't over-think it, and instead just demonstrate how the operators don't conform to the algorithm without trying to fix anything.
Suppose your code naively uses C++ operators to calculate q and r as follows:
int q = a / d;
int r = a % d;
You then get wrong (in this case, wrong just means they don't "conform" to your algorithm) values for both q and r in the following two cases:
a = -17, b = 3
The code will result in:
q = -5, r = 2
This does not conform to the division algorithm because
-5 * 3 + 2 = -13 so you clearly have the wrong q and r.
a = -17, b = -3
The code will result in:
q = 5, r = -2
This does not conform to the division algorithm because there is a rule that 0 <=
r < |d|. In other words, r must be positive.
In the other cases, i.e. where both a and d are positive or when a is positive and d is negative, the C++ operators will correctly "conform" to your algorithm.
The C++ integer division operator gives the correct result only if both dividend and divisor are positive. This because it always rounds toward zero
As the question doesn't clearly states the problem I presume you want to output the devision like the examples provided, so a simple code would be:
int a=17;
int b=-3;
cout<<"If a="<<a<<"and b="<<b<<"then q="<<a/b<<"and r="<<a%b;
Related
Hi I am writing a code to calculate P^Q where
P, Q are positive integers which can have number of digits upto 100000
I want the result as
result = (P^Q)modulo(10^9+7)
Example:
P = 34534985349875439875439875349875
Q = 93475349759384754395743975349573495
Answer = 735851262
I tried using the trick:
(P^Q)modulo(10^9+7) = (P*P*...(Q times))modulo(10^9+7)
(P*P*...(Q times))modulo(10^9+7) = ((Pmodulo(10^9+7))*(Pmodulo(10^9+7))...(Q times))modulo(10^9+7)
Since both P and Q are very large, I should store them in an array and do modulo digit by digit.
Is there any efficient way of doing this or some number theory algorithm which I am missing?
Thanks in advance
Here is a rather efficient way:
1)Compute p1 = P modulo 10^9 + 7
2)Compute q1 = Q modulo 10^9 + 6
3)Then P^Q modulo 10^9 + 7 is equal to p1^q1 modulo 10^9 + 7. This equality is true because of Fermat's little theorem. Note that p1 and q1 are small enough to fit in 32-bit integer, so you can implement binary exponention with standard integer type(for intermidiate computations, 64-bit integer type is sufficient because initial values fit in 32-bits).
Where I need help...
What I want to do now is translate this solution, which calculates the mantissaof a number to c++:
n^m = exp10(m log10(n)) = exp(q (m log(n)/q)) where q = log(10)
Finding the first n digits from the result can be done like this:
"the first K digits of exp10(x) = the first K digits of exp10(frac(x))
where frac(x) = the fractional part of x = x - floor(x)."
My attempts (sparked by the math and this code) failed...:
u l l function getPrefix(long double pow /*exponent*/, long double length /*length of prefix*/)
{
long double dummy; //unused but necessary for modf
long double q = log(10);
u l l temp = floor(pow(10.0, exp(q * modf( (pow * log(2)/q), &dummy) + length - 1));
return temp;
}
If anyone out there can correctly implement this solution, I need your help!!
EDIT
Example output from my attempts:
n: 2
m: 0
n^m: 1
Calculated mantissa: 1.16334
n: 2
m: 1
n^m: 2
Calculated mantissa: 2.32667
n: 2
m: 2
n^m: 4
Calculated mantissa: 4.65335
n: 2
m: 98
n^m: 3.16913e+29
Calculated mantissa: 8.0022
n: 2
m: 99
n^m: 6.33825e+29
Calculated mantissa: 2.16596
I'd avoid pow for this. It's notoriously hard to implement correctly. There are lots of SO questions where people got burned by a bad pow implementation in their standard library.
You can also save yourself a good deal of pain by working in the natural base instead of base 10. You'll get code that looks like this:
long double foo = m * logl(n);
foo = fmodl(foo, logl(10.0)) + some_epsilon;
sprintf(some_string, "%.9Lf", expl(foo));
/* boring string parsing code here */
to compute the appropriate analogue of m log(n). Notice that the largest m * logl(n) that can arise is just a little bigger than 2e10. When you divide that by 264 and round up to the nearest power of two, you see that an ulp of foo is 2-29 at worst. This means, in particular, that you cannot get more than 8 digits out of this method using long doubles, even with a perfect implementation.
some_epsilon will be the smallest long double that makes expl(foo) always exceed the mathematically correct result; I haven't computed it exactly, but it should be on the order of 1e-9.
In light of the precision difficulties here, I might suggest using a library like MPFR instead of long doubles. You may also be able to get something to work using a double double trick and quad-precision exp, log, and fmod.
I am trying to calculate below expression for large numbers.
Since the value of this expression will be very large, I just need the value of this expression modulus some prime number. Suppose the value of this expression is x and I choose the prime number 1000000007; I'm looking for x % 1000000007.
Here is my code.
#include<iostream>
#define MOD 1000000007
using namespace std;
int main()
{
unsigned long long A[1001];
A[2]=2;
for(int i=4;i<=1000;i+=2)
{
A[i]=((4*A[i-2])/i)%MOD;
A[i]=(A[i]*(i-1))%MOD;
while(1)
{
int N;
cin>>N;
cout<<A[N];
}
}
But even this much optimisation is failing for large values of N. For example if N is 50, the correct output is 605552882, but this gives me 132924730. How can I optimise it further to get the correct output?
Note : I am only considering N as even.
When you do modular arithmetic, there is no such operation as division. Instead, you take the modular inverse of the denominator and multiply. The modular inverse is computed using the extended Euclidean algorithm, discovered by Etienne Bezout in 1779:
# return y such that x * y == 1 (mod m)
function inverse(x, m)
a, b, u := 0, m, 1
while x > 0
q, r := divide(b, x)
x, a, b, u := b % x, u, x, a - q * u
if b == 1 return a % m
error "must be coprime"
The divide function returns both quotient and remainder. All of the assignment operators given above are simultaneous assignment, where all of the right hand sides are computed first, then all of the left hand sides are assigned simultaneously. You can see more about modular arithmetic at my blog.
For starters no modulo division is needed at all, your formula can be rewrited as follows:
N!/((N/2)!^2)
=(1.2.3...N)/((1.2.3...N/2)*(1.2.3...N/2))
=((N/2+1)...N)/(1.2.3...N/2))
ok now you are dividing bigger number by the smaller
so you can iterate the result by multiplicating divisor and divident
so booth sub results have similar magnitude
any time both numbers are divisible 2 shift them left
this will ensure that the do not overflow
if you are at the and of (N/2)! than continue the the multiplicetion only for the rest.
any time both subresults are divisible by anything divide them
until you are left with divison by 1
after this you can multiply with modulo arithmetics till the end normaly.
for more advanced approach see this.
N! and (N/2)! are decomposable much further than it seems at the first look
i had solved that for some time now,...
here is what i found: Fast exact bigint factorial
in shortcut your terms N! and ((N/2)!)^2 will disappear completely.
only simple prime decomposition + 4N <-> 1N correction will remind
solution:
I. (4N!)=((2N!)^2) . mul(i=all primes<=4N) of [i^sum(j=1,2,3,4,5,...4N>=i^j) of [(4N/(i^j))%2]]
II. (4N)!/((4N/2)!^2) = (4N)!/((2N)!^2)
----------------------------------------
I.=II. (4N)!/((2N)!^2)=mul(i=all primes<=4N) of [i^sum(j=1,2,3,4,5,...4N>=i^j) of [(4N/(i^j))%2]]
the only thing is that N must be divisible by 4 ... therefore 4N in all terms.
if you have N%4!=0 than solve for N-N%4 and the result correct by the misin 1-3 numbers.
hope it helps
So I am learning C++, and in one of the books I'm reading, there is an example for finding GCF (greatest common factor). The function is as follows:
int gcf(int a, int b) {
if(b == 0) {
return a;
}
else {
return gcf(b, a%b);
}
}
What I don't understand is that if I put in 15 and 5 for example, then
a = 15
b = 5
b is not 0 so then the else statement executes
(5, 15%5 = 0) so since b is now 0 it returns, a, which is 5.
That makes sense, but if I reverse the numbers, why/how do I get the same answer?
a = 5
b = 15
b is not 0 so then the else statement executes
(15, 5%15) but 5%15 is .3 or 1/3, but in C++, 5%15 returns 5.
I don't understand where 5 comes from, if anything, since it's an integer, I thought it maybe return 0 but it doesn't return 15, so it can't be.
What you're doing is integer calculation - no floating points or fractions involved.
5 % 15 is actually the remainder you get after dividing 5 by 15, and that is, of course, 5 (the quotient would be 0).
15 | 5 | 0 <-- this is the first call gcf(5, 15)
0
---
5 | 15 | 3 <-- this is the first recursive call gcf(15, 5)
15
---
0 | 5 | <-- this is the second recursive call gcf(5, 0), returns 5
Modulo operator is different from division,usually when we divide the return value is a quotient but when you use modulo operator return value is its reminder.
so in your case when
**
a=5 and b = 15, a%b the return value of this was 0 ,
**
that is the reason why it returned 5. check the following links for greater clarity on modulo operator
http://www.cplusplus.com/doc/tutorial/operators/
http://www.cprogramming.com/tutorial/modulus.html
In integer division, 5/15 = 0. Since 5%15 is the remainder, it needs to be 5. C and C++ mandate that for any a and b, a/b*b + a%b = a.
If you are interested, the piece of code you have written there is called Euclid's Algorithm which is based upon Euclid's Lemma (big surprise there). Although I heard from a professor that some people might refer to different formulations of Euclid's Lemma. My Higher Algebra book particularly refers to it as "Equal gcd's".
It states:
Let a, b, q, and c be integers with a=qb+c. Then gcd(a,b)=gcd(b,c)
gcd(a,b) refers to the greatest common divisor of a and b.
This seems to be precisely what you are doing in your program.
Any integer a can be written as the qb+c for any b. This means that a is a product qb plus some remainder c. The remainder here is what you are calculating when you use the % operator. If we let a = 12 and b = 5 then can write 12=5q+c. Let q be 2. Then our remainder c is 2. Perhaps these things are elementary but hopefully this is nice background to supplement your book's explanation.
I am trying to implement a simple decimation algorithm in c++. I have two arrays, say p & q, where the subscripts are related to each other by the following relation:
p[k] = q[0.5*k]. This means that the following sequence should hold valid:
p[0] = q[0]
p[1] = 0
p[2] = q[1]
p[3] = 0
p[4] = q[2]
and so on...
Please note that p[k] takes on a value only and only when the result of (0.5*k) contains no decimal places (or has 0 in decimal) and does not use any rounding off etc.
My question is: Is there a way to distinguish between an integer (a number with no decimal places or only 0 in decimal, say 2.0) and a number with decimal places in C++, provided both are cast to double?
eg.) 2.0 is an integer cast to double. 2.1 is a number with decimal places.
eg. 2) * 0.9*2 should put 0 into array p while 0.9*10 should put q[9] into array p.*
If I use the statement, (int) (0.5*k), then I end up with an integer in every case, irrespective of the value of k.
Edit: The 0.5 in the above case is only illustrative. It could be any number, say 2, 2.5, 0.9, 0.95 etc.)
Any help is most welcome,
Thanks,
Sriram.
Assuming k is of an integer type, you could use if (k % 2 == 0) ... to check if kis divisible by two:
if (k % 2 == 0)
p[k] = q[k / 2];
else
p[k] = 0;
This can also be expressed using the ternary operator:
p[k] = (k % 2 == 0) ? q[k / 2] : 0;
Presuming that the coef can be anything else,
p[floor(coef*k)] = (fabs(coef*k-floor(coef*k))<1E-6)?q[k]:0;
The short syntax for what you want to do could be this:
p[k] = k % 2 ? 0 : q[k/2];
Is there a way to distinguish between a whole number and an integer in C++?
Define whole number, and define integer in this context. I'm confused!
Are you taking about the difference as explained here?
If you want to detect whether a number is integer or not, then probably this may help:
#include<cmath>
bool IsInteger(double d)
{
double intpart;
return std::modf(double number, &intpart) == 0.0;
}
k % 2 is in a couple of answers in this thread.
However, this is not useful in answering the OP's question. Note the edit:
"Edit: The 0.5 in the above case is only illustrative. It could be any number, say 2, 2.5, 0.9, 0.95 etc.)"
k % 2 only works because the value chosen was 0.5. It won't hold true for any other values.
Therefore, unless I'm missing something entirely, the simplest approach I can think of is the following:
Subtract the floor of the number from the number itself. If the result is > 0, it is not an integer.
Unless you have expressions that result in irrational numbers, you could use Boost.Rational to represent your indizes.
#Aix's suggestion of k%2 looks like it'd combine nicely with the ?: operator:
p[k] = (k%2) ? 0 : q[k/2];