Array Division - What is the best way to divide two numbers stored in an array? - c++

I have two arrays (dividend, divisor):
dividend[] = {1,2,0,9,8,7,5,6,6};
divisor[] = {9,8};
I need the result (dividend/divisor) as:
quotient[] = {1,2,3,4,5,6,7};
I did this using array subtraction:
subtract divisor from dividend until dividend becomes 0 or less than divisor, each time incrementing quotient by 1,
but it takes a huge time. Is there a better way to do this?

Do long division.
Have a temporary storage of size equal to the divisor plus one, and initialized to zero:
accumulator[] = {0,0,0};
Now run a loop:
Shift each digit of the quotient one space to the left.
Shift each digit of the accumulator one space to the right.
Take the next digit of the dividend, starting from the most-significant end, and store it to the least-significant place of the accumulator.
Figure out accumulator / divisor and set the least-significant place of the quotient to the result. Set the accumulator to the remainder.
Used to use this same algorithm a lot in assembly language for CPUs what didn't have division instructions.

Other than that, have you considered using BigInt class (or the equivalent thing in your language) which will already does this for you?

You can use long division http://en.wikipedia.org/wiki/Long_division

Is there a better way to do this?
You can use long division.

You can use Long division algorithm or the more general Polynomial Long Division.

Why not convert them to integers and then use regular division?
in pseudocode:
int dividend_number
foreach i in dividend
dividend_number *= 10
dividend_number += i
int divisor_number
foreach i in divisor
divisor_number *= 10
divisor_number += i
int answer = dividend_number / divisor_number;

There you go!
A is the divident.
B is the divisor.
C is the integer quotinent
R is the rest.
Each "huge" number is a vector retaining a big number. In huge[0] we retain the number of digits the number has and thren the number is memorized backwards.
Let's say we had the number 1234, then the corespoding vector would be:
v[0]=4; //number of digits
v[1]=4;
v[2]=3;
v[3]=2;
v[4]=1;
....
SHL(H,1) does: H=H*10;
SGN(A,B) Compares the A and B numbers
SUBSTRACT(A,B) does: A=A-B;
DIVIDHUGE: makes the division using the mentioned procedures...
void Shl(Huge H, int Count)
/* H <- H*10ACount */
{
memmove(&H[Count+1],&H[1],sizeof(int)*H[0]);
memset(&H[1],0,sizeof(int)*Count);
H[0]+=Count;
}
int Sgn(Huge H1, Huge H2) {
while (H1[0] && !H1[H1[0]]) H1[0]--;
while (H2[0] && !H2[H2[0]]) H2[0]--;
if (H1[0] < H2[0]) {
return -1;
} else if (H1[0] > H2[0]) {
return +1;
}
for (int i = H1[0]; i > 0; --i) {
if (H1[i] < H2[i]) {
return -1;
} else if (H1[i] > H2[i]) {
return +1;
}
}
return 0;
}
void Subtract(Huge A, Huge B)
/* A <- A-B */
{ int i, T=0;
for (i=B[0]+1;i<=A[0];) B[i++]=0;
for (i=1;i<=A[0];i++)
A[i]+= (T=(A[i]-=B[i]+T)<0) ? 10 : 0;
while (!A[A[0]]) A[0]--;
}
void DivideHuge(Huge A, Huge B, Huge C, Huge R)
/* A/B = C rest R */
{ int i;
R[0]=0;C[0]=A[0];
for (i=A[0];i;i--)
{ Shl(R,1);R[1]=A[i];
C[i]=0;
while (Sgn(B,R)!=1)
{ C[i]++;
Subtract(R,B);
}
}
while (!C[C[0]] && C[0]>1) C[0]--;
}

Related

How to get rid of 2 numbers' common divisors

So I have a function that divides a pair of numbers until they no longer have any common divisors:
void simplify(int &x, int &y){
for (int i = 2;;++i){
if (x < i && y < i){
return;
}
while (1){
if (!(x % i) && !(y % i)){
x /= i;
y /= i;
} else {
break;
}
}
}
}
How can I make it more efficient? I know one problem in this solution is that it tests for divisibility with compound numbers, when it wouldn't have any of it's factors by the time it gets to them, so it's just wasted calculations. Can I do this without the program knowing a set of primes beforehand/compute them during the function's runtime?
Use the Euclidean algorithm1:
Let a be the larger of two given positive integers and b be the smaller.
Let r be the remainder of a divided by b.
If r is zero, we are done, and b is the greatest common divisor.
Otherwise, let a take the value of b, let b take the value of r, and go to step 2.
Once you have the greatest common divisor, you can divide the original two numbers by it, which will yield two numbers with the same ratio but without any common factors greater than one.
Citation
1 Euclid, Elements, book VII, propositions 1 and 2, circa 300 BCE.
Notes
Euclid used subtraction, which has been changed here to remainder.
Once this algorithm is working, you might consider the slightly more intricate Binary GCD, which replaces division (which is slow on some processors) with subtraction and bit operations.
Sounds like a job for the C++17 library feature gcd.
#include <numeric>
void simplify(int &x, int &y)
{
const auto d = std::gcd(x, y);
x /= d;
y /= d;
}
Compiler Explorer

Calculate floor(pow(2,n)/10) mod 10 - sum of digits of pow(2,n)

This is also a math related question, but I'd like to implement it in C++...so, I have a number in the form 2^n, and I have to calculate the sum of its digits ( in base 10;P ). My idea is to calculate it with the following formula:
sum = (2^n mod 10) + (floor(2^n/10) mod 10) + (floor(2^n/100) mod 10) + ...
for all of its digits: floor(n/floor(log2(10))).
The first term is easy to calculate with modular exponentiation, but I'm in trouble with the others.
Since n is big, and I don't want to use my big integer library, I can't calculate pow(2,n) without modulo. A code snippet for the first term:
while (n--){
temp = (temp << 1) % 10;
};
but for the second I have no idea. I also cannot floor them individually, since it would give '0' (2/10). Is it possible to achieve this?
(http://www.mathblog.dk/project-euler-16/ for the easier solution.) Of course I will look for other way if it cannot be done with this method. (for example storing digits in byte array, as in the comment in the link).
Edit: Thanks for the existing answers, but I look for some way to solve it mathematically. I've just came up with one idea, which can be implemented without bignum or digit-vectors, I'm gonna test if it works.
So, I have the equation above for the sum. But 2^n/10^k can be written as 2^n/2^(log2 10^k) which is 2^(n-k*log2 10). Then I take it's fractional part, and its integer part, and do modular exponentiation on the integer part: 2^(n-k*log2 10) = 2^(floor(n-k*log2 10)) * 2^(fract(n-k*log2 10)). After the last iteration I also multiply it with the fractional modulo 10. If it won't work or if I'm wrong somewhere in the above idea, I stick to the vector solution and accept an answer.
Edit: Ok, it seems doing modular exponentiation with non-integer modulo is not possible(?) (or I haven't found anything about it). So, I'm doing the digit/vector based solution.
The code does NOT work fully!
It does not give the good value: (1390 instead of 1366):
typedef long double ldb;
ldb mod(ldb x, ldb y){ //accepts doubles
ldb c(0);
ldb tempx(x);
while (tempx > y){
tempx -= y;
c++;
};
return (x - c*y);
};
int sumofdigs(unsigned short exp2){
int s = 0;
int nd = floor((exp2) * (log10(2.0))) + 1;
int c = 0;
while (true){
ldb temp = 1.0;
int expInt = floor(exp2 - c * log2((ldb)10.0));
ldb expFrac = exp2 - c * log2((ldb)10.0) - expInt;
while (expInt>0){
temp = mod(temp * 2.0, 10.0 / pow(2.0, expFrac)); //modulo with non integer b:
//floor(a*b) mod m = (floor(a mod (m/b)) * b) mod m, but can't code it
expInt--;
};
ldb r = pow(2.0, expFrac);
temp = (temp * r);
temp = mod(temp,10.0);
s += floor(temp);
c++;
if (c == nd) break;
};
return s;
};
You could create a vector of the digits using some of the techniques mentioned in this other question (C++ get each digit in int) and then just iterate over that vector and add everything up.
In the link you mention, you have the answer which will work as is for any number with n <= 63. So... why do you ask?
If you have to program your own everything then you need to know how to calculate a binary division and handle very large numbers. If you don't have to program everything, get a library for large integer numbers and apply the algorithm shown in the link:
BigNumber big_number;
big_number = 1;
big_number <<= n;
int result = 0;
while(big_number != 0) {
result += big_number % 10;
big_number /= 10;
}
return result;
Now, implementing BigNumber would be fun. From the algorithm we see that you need assignment, shift to left, not equal, modulo and division. A BigNumber class can be fully dynamic and allocate a buffer of integers to make said big number fit. It can also be written with a fixed size (as a template for example). But if you don't have the time, maybe this one will do:
https://mattmccutchen.net/bigint/
I implemented this in JavaScript as below for finding the sum of digits of 2^1000: (Check out working CodePen)
function calculate(){
var num = 0, totalDigits = 1,exponent =0,sum=0,i=0,temp=0, carry;
var arr = ['1'];
//Logic to implement how we multiply in daily life using carry forward method
while(exponent<1000){ //Mention the power
carry=0;
for(var j=arr.length-1;j>=0;j--){
temp = arr[j]*2 + carry;
arr[j]= temp%10;
carry = parseInt(temp/10);
if(carry && !j){
arr = [carry].concat(arr); //if the last nth digit multiplication with 2 yields a carry, increase the space!
}
}
exponent++;
}
for(var i=0;i<arr.length;i++){
sum = sum+parseInt(arr[i]);
}
document.getElementById('result').value = sum; //In my HTML code, I am using result textbox with id as 'result'
//console.log(arr);
//console.log(sum);
}

Best program for Permutation nPr of large numbers

I am new to programming and was stuck at the permutation part. I have code which works for combination of large numbers which is stored in matrix but i am not able to find what should i change in that to get the result.
I tried the recursive method for permutations but could not achieve fast results.
This is the code which i got for combination what should be the change in condition which i should do here to get permutations?
void combination()
{
int i,j;
for(i=0;i<100;i++)
{
nCr[i][0]=1;
nCr[i][i]=1;
}
for(i=1;i<100;i++)
for(j=1;j<100;j++)
if (i!=j)
{
nCr[i][j] = (nCr[i-1][j] + nCr[i-1][j-1]);
}
}
A recurrence rule for permutations can be easily derived from the definition:
nPk = n*(n-1)*(n-2)* ... * (n-k+1) = n * (n-1)P(k-1)
Converted to code:
for(i=0;i<100;i++)
{
nPr[i][0]=1;
}
for(i=1;i<100;i++)
for(j=1;j<100;j++)
if (i!=j)
{
nPr[i][j] = i * nPr[i-1][j-1];
}
Note that the number of permutations grows fast and overflows the storage available for int: 13P11 for example is already out of range with signed 32bit integers.
well you can use the following pseudo-code for computing permutation and combination given that mod is always a very large prime number.
for permutation nPr
func permutation(r,n,mod):
q=factorial(n) // you should precompute them and saved in an array for a better execution time
r=(factorial(r))%mod
return (q*math.pow(r,mod-2))%mod
for combination nCr
func combination(r,n,mod):
q=factorial(n)
r=(factorial(r)*factorial(n-r))%mod
return (q*math.pow(r,mod-2))%mod
your should precompute factorials , for a decent execution time.
fact[100000]
fact[0]=fact[1]=1
func factorial_compute():
for x from 2 to 100000:
fact[x]=(x*fact[x-1])%mod
hence your factorial function will be
func factorial(x):
return(fact[x])
for reference on mathematics for this : http://mathworld.wolfram.com/ModularInverse.html
Actually, I know where the problem raised
At the point where we multiply , there is the actual problem ,when numbers get multiplied and get bigger and bigger.
this code is tested and is giving the correct result.
#include <bits/stdc++.h>
using namespace std;
#define mod 72057594037927936 // 2^56 (17 digits)
// #define mod 18446744073709551616 // 2^64 (20 digits) Not supported
long long int prod_uint64(long long int x, long long int y)
{
return x * y % mod;
}
int main()
{
long long int n=14, s = 1;
while (n != 1)
{
s = prod_uint64(s , n) ;
n--;
}
}

How make this even count code faster?

The following code is meant to find total numbers between l and r whose product of digits is even (for multiple test cases t). This code runs perfectly but is extremely slow for r greater than 100000. Can anyone suggest a better alternative?
#include <iostream>
#include <algorithm>
using namespace std;
long long int nd(long long int x, int n) //return the digit at a particular index staring with zero as index for unit place
{
while (n--) {
x /= 10;
}
return (x % 10);
}
int ng(long long int number) //returns total number of digits in an integer
{
int digits = 0;
if (number < 0) digits = 1;
while (number) {
number /= 10;
digits++;
}
return digits;
}
int main()
{
int t;
cin>>t;
long long int l[t], r[t], c;
for(long long int j=0;j<t;j++)
{
cin>>l[j]>>r[j];
}
for(long long int k=0;k<t;k++)
{
long long int sum=0;
long long int t=0;
for(long long int i=l[k];i<=r[k];i++)
{
while(t<ng(i))
{
c=nd(i,t);
if((c%2)==0)
{
++sum;
break;
}
++t;
}
t=0;
}
cout<<sum<<endl;
}
cin.ignore();
cin.get();
return 0;
}
The basic idea is to loop through each digit of a number and see if it's even. If it is, the whole product will be even and there's no need to check the remaining digits.
The problem with your code is that you run trough the number multiple times looking for a digit with index i. You should simply run through the number's digits once checking for evenness along the way.
Here's a self-explanatory Go code implementing the algorithm:
package main
func iseven(num int) bool {
for num > 0 {
digit := num % 10
if digit&1 == 0 { # same as digit%2 == 0, only simpler
return true
}
num /= 10
}
return false
}
func main() {
sum := 0
for n := 1; n < 1000000; n++ {
if iseven(n) {
sum++
}
}
println(sum)
}
Performance on my machine:
λ time go run main.go
980469
go run main.go 0.05s user 0.01s system 81% cpu 0.073 total
Update
If you need to work with ginormous numbers, then a more efficient approach can be used.
Let's call the numbers that have the product of their digits odd dodd numbers. So, 135 is a dodd number, 134 is not. Similarly, numbers that have the product of their digits even are called deven. So 134 is a deven number.
As has been mentioned earlier, only numbers that consist of odd digits are dodd. So instead of enumerating numbers, we can just count the numbers comprised of digits 1, 3, 5, 7, and 9. For integer N > 1, there are exactly 10^N - 10^(N-1) numbers that have N digits. And of those numbers, 5 ^ N are dodd, and therefore 10^N - 10^(N-1) - 5^N are deven.
The approach is to count how many dodd numbers there are in between the left and right bounds and then subtract that count from the total count of numbers between left and right. You could also count just deven numbers, but that is a bit trickier.
Effectively, you're going to loop through digits with this approach, instead of through numbers. My implementation in Python is able to compute the number of deven numbers between 1 and int("1" * 100000) (a number with 10000 digits) in under one second.
All numbers starting with, e.g., 10…, 12…, 14…, …, 2…, 30…, already are known to have an even product of digits. I would therefore start from the left (more significant digits) and count in blocks. There are only a few numbers whose product of digits is odd (such as 1111111111), only here you have to dig deeper.
Here is some pseudocode:
int count(String prefix, int digits) {
int result = 0;
if (digits == 0)
return 0;
for (int d = 0; d < 10; d++) {
if (d%2 == 0)
result += 10**(digits-1);
else
result += count(prefix . toString(d), digits-1);
}
return result;
}
This would be called like count("2", 8) to get the count for the interval from 200000000 to 299999999.
Here is a Haskell implementation for a whole block (i.e., all d-digit numbers):
blockcount :: Integer -> Integer
blockcount 0 = 0
blockcount d = 5 * 10^(d-1) + 5 * blockcount (d-1)
E.g., blockcount 1000 is calculated to be 9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999066736381496781121009910455276182830382908553628291975378285660204033089024224365545559672902118897640405010069675757375784512478645967605158479182796069243765589333861674849726004924014098168488899509203734886881759487485204066209194821728874584896189301621145573518880530185771339040777982337089557201543830551112852533471993671631547352570738170137834797206804710506392882149336331258934560194469281863679400155173958045898786770370130497805485390095785391331638755207047965173135382342073083952579934063610958262104177881634921954443371555726074612482872145203218443653596285122318233100144607930734560575991288026325298250137373309252703237464196070623766166018953072125441394746303558349609375 in much less than a second.
You’d still have to add code that breaks your range into suitable blocks.
An optimisation based on the following would work:
Multiplying two numbers together gets you oddness / evenness according to the rule
even * even = even
odd * even = even * odd = even
odd * odd = odd
Therefore you only need to track the last digit of your number numbers.
I'm too old to code this but I bet it would be blisteringly quick as you only need to consider numbers between 0 and 9.
The only thing you need to check is if one of digits in the number is even. If it is, it will have 2 as a factor, and hence be even.
You also don't seem to remember where you are up to in digits - every time you increment t in your for loop, and then call nd(i,t), you count down from that t to zero in nd. This is quadratic in number of digits in the worst case. Better would be to simply break up the number into its component digits at the beginning.
I can't figure out what your code is doing, but the basic
principles are simple:
value % 10 is the low order digit
value /= 10 removes the low order digit
if any digit is even, then the product will be even.
This should lead to a very simple loop for each value. (You may
have to special case 0.)
Further optimizations are possible: all even numbers will have
a product of digits which is even, so you can iterate with
a step of 2, and then add in the number of evens (one half of
the range) afterwards. This should double the speed.
One further optimization: if the low order digit is even, the number itself is even, so you don't have to extract the low order digit to test it.
Another thing you could do is change
while(t<ng(i))
to
int d = ng(i);
while (t < d)
So ng is only called once per loop.
Also ng is just log(number)+1 (log base 10 that is)
I don't know is that will be quicker though.
First, please fix your indentation
Your code uses too many division and loops which cause a lot of delays
long long int nd(long long int x, int n) //return the digit at a particular index staring with zero as index for unit place
{
while (n--) {
x /= 10;
}
return (x % 10);
}
This can be fixed easily by a table lookup
long long int nd(long long int x, int n) //return the digit at a particular index staring with zero as index for unit place
{
long long int pow10[] = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000,
100000000, 1000000000, 10000000000, 100000000000,
1000000000000, 10000000000000, 100000000000000,
1000000000000000, 10000000000000000,
100000000000000000, 1000000000000000000};
return ((x / pow10[n]) % 10);
}
Likewise, the ng function to get total number of digits in an integer can be changed to a fast log10, no need to repeatedly divides and count. Ofcourse it'll need a small change to adapt 64 bit numbers
int ng(long long int number) //returns total number of digits in an integer
{
int digits = 0;
if (number < 0) digits = 1;
while (number) {
number /= 10;
digits++;
}
return digits;
}

Coding Competitions: How to store large numbers and find its all combination modulus P

I have started doing competitive programming and most of the time i find that the input size of numbers is like
1 <= n <= 10^(500).
So i understand that it would be like 500 digits which can not be stored on simple int memory. I know c and c++.
I think i should use an array. But then i get confused on how would i find
if ( (nCr % P) == 0 ) //for all (0<=r<=n)//
I think that i would store it in an array and then find nCr. Which would require coding multiplication and division on digits but what about modulus.
Is there any other way?
Thanks.
I think you don't want to code the multiplication and division yourself, but use something like the GNU MP Bignum library http://gmplib.org/
Regarding large number libraries, I have used ttmath, which provides arbitrary length integers, floats, etc, and some really good operations, all with relatively little bulk.
However, if you are only trying to figure out what (n^e) mod m is, you can do this for very large values of e even without extremely large number calculation. Below is a function I added to my local ttmath lib to do just that:
/*!
mod power this = (this ^ pow) % m
binary algorithm (r-to-l)
return values:
0 - ok
1 - carry
2 - incorrect argument (0^0)
*/
uint PowMod(UInt<value_size> pow, UInt<value_size> mod)
{
if(pow.IsZero() && IsZero())
// we don't define zero^zero
return 2;
UInt<value_size> remainder;
UInt<value_size> x = 1;
uint c = 0;
while (pow != 0)
{
remainder = (pow & 1 == 1);
pow /= 2;
if (remainder != 0)
{
c += x.Mul(*this);
x = x % mod;
}
c += Mul(*this);
*this = *this % mod;
}
*this = x;
return (c==0)? 0 : 1;
}
I don't believe you ever need to store a number larger than n^2 for this algorithm. It should be easy to modify such that it removes the ttmath related aspects, if you don't want to use those headers.
You can find the details of the mathematics online by looking up modular exponentiation, if you care about it.
If we have to calcuate nCr mod p(where p is a prime), we can calculate factorial mod p and then use modular inverse to find nCr mod p. If we have to find nCr mod m(where m is not prime), we can factorize m into primes and then use Chinese Remainder Theorem(CRT) to find nCr mod m.
#include<iostream>
using namespace std;
#include<vector>
/* This function calculates (a^b)%MOD */
long long pow(int a, int b, int MOD)
{
long long x=1,y=a;
while(b > 0)
{
if(b%2 == 1)
{
x=(x*y);
if(x>MOD) x%=MOD;
}
y = (y*y);
if(y>MOD) y%=MOD;
b /= 2;
}
return x;
}
/* Modular Multiplicative Inverse
Using Euler's Theorem
a^(phi(m)) = 1 (mod m)
a^(-1) = a^(m-2) (mod m) */
long long InverseEuler(int n, int MOD)
{
return pow(n,MOD-2,MOD);
}
long long C(int n, int r, int MOD)
{
vector<long long> f(n + 1,1);
for (int i=2; i<=n;i++)
f[i]= (f[i-1]*i) % MOD;
return (f[n]*((InverseEuler(f[r], MOD) * InverseEuler(f[n-r], MOD)) % MOD)) % MOD;
}
int main()
{
int n,r,p;
while (~scanf("%d%d%d",&n,&r,&p))
{
printf("%lld\n",C(n,r,p));
}
}
Here, I've used long long int to stote the number.
In many. many cases in these coding competitions, the idea is that you don't actually calculate these big numbers, but figure out how to answer the question without calculating it. For example:
What are the last ten digits of 1,000,000! (factorial)?
It's a number with over five million digits. However, I can answer that question without a computer, not even using pen and paper. Or take the question: What is (2014^2014) modulo 153? Here's a simple way to calculate this in C:
int modulo = 1;
for (int i = 0; i < 2014; ++i) modulo = (modulo * 2014) % 153;
Again, you avoided doing a calculation with a 6,000 digit number. (You can actually do this considerably faster, but I'm not trying to enter a competition).