How to solve this easy in c or c++? [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
print 10**1000 % 7
In C I get a syntax error because it exceeds the memory limit I guess. Can I somehow solve this easy in C or C++, such that it would give me a modulo of 10 to the power of 1000?

In addition to that not being valid syntax in C/C++, it's bad practice in python.
If you do
pow(10,1000,7)
It will use modular exponentiation so it will be much faster than doing
10 ** 1000 % 7

you can use pow for power operation. here the size of result is large value so you need to divide the problem into smaller part and solve smaller ones to get the solution in c or you'll need to handle large numbers.
you can apply modulus rules to reduce the problem as,
10^1000 % 7 =((10%7)^1000)%7
10^1000 % 7 =(((((10^10)%7)^10)%7)^10)%7
combine these rules and use to reduce the numbers generated in steps by (mod 10).use inbuilt pow() function in c to get power of number as X^y=pow(x,y)

The most general way to solve these types of big-integer problems in small (e.g. 32-bit) registers is with exponentiation by squaring, and taking modulo at each step. E.g. 10^10 is still too big to fit in a 32-bit int, though you could probably just use a long these days.

In C (and C++ too AFAIK) this is not a valid syntax. You can use pow function for exponentiation. But keep in mind that return value of pow is double and modulo operator works for int. You need some cautions.
long result = (long)pow(10, 1000);
result = result % 7;

The easiest way to do this is to reduce the terms by the modulus. The general formula is
ab mod c ≡ (a mod c)(b mod φ(c)) mod c
So in this case you get
101000 mod 7 = (10 mod 7)(1000 mod φ(7)) mod 7.
10 mod 7 = 3
φ(7) = 6
1000 mod 6 = 4
34 = 81
81 mod 7 = 4
so 101000 mod 7 = 4

in C and C++ there's no ** operator, you have to use the pow function, that however works only for floating-point types; and the % operator works only for integral types, for FP types you have to use fmod;
anyhow, if you have insert some constant 10**n you would just write 1En (say, 1E42);
.... but there's no standard type able to hold a number as big as 1E1000; even if some FP type were able to hold it, you couldn't reliably use fmod on it, due to the finite precision of the mantissa.
So, how does Python do? Under the hood, beyond the range of "normal" types it uses an arbitrary precision library. You can do the same in your C++ program, providing such library (for example you could use GMP).
But: the expression you provide can be calculated without actually computing 10**1000 and its modulus. Read Modulus power of big numbers

Related

How to find out how many bits are set (equal 1) in the product of two integers [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I am looking for an algorithm solution to find out how many bits are set (equal 1) if I multiply two integers. I have numbers A and B, between 0 and MAX_INT, to eliminate the negative numbers. How do I find out how many bits will be set in the product C = A * B.
-of course calculating C and counting the bits is not the correct solution, it won't work for high values
-I work in C and C++, but it is a rather general algorithm problem. I must solve it without any math/boost library help.
Tried finding a general solution to know the bit count, but what I guessed only worked for quite some examples, it entirely failed with high numbers.
The question asks for an algorithm. The problem can be solved without holding a complete product, by computing each bit at a time, starting with bit 0.
Bit C0 is found from the product of A0 * B0 and is either 0 or 1.
Bit C1 is found from the sum of the products A0 * B1 + A1 * B0 and remembering any carry.
Bit C2 is found from the sum of carry + A0 * B2 + A1 * B1 + A2 * B0 and so on.
As you go, you sum the single product bits, which gives the required answer: number of set bits.
There seems to be no general solution to your problem that would be simpler than performing the multiplication and counting the bits in the result. If the numbers are really large, the multiplication can be performed in slices at a significant cost in execution time.
There are however some special cases you might find useful:
if either A or B has exactly 0 bits set (A == 0 or B == 0), then C will have 0 bits set (C == 0), and this is the only way for C to have 0 bits set.
if either A or B has exactly 1 bit set (A or B is a power of 2), then C will have the same number of bits set as the other number. Furthermore, for C to have exactly 1 bit set, both A and B must be powers of 2.
the number of bits set in C is less than the sum of the numbers of significant bits in A and B.
the number of unset least significant bits in C is the sum of the number of unset least significant bits in A plus the number of unset least significant bits in C.
There is no simple general solution for this.
e.g. see the following multiplication
3(0b0011) * 4(0b0100) = 12(0b1100)
3(0b0011) * 5(0b0101) = 15(0b1111)
3(0b0011) * 6(0b0110) = 18(0b10010)
The reason is that there may be some carry bits in the multiplication which will ripple through the output and change the number of ones in unpredictable ways.
You need to do the multiplication, and then count the bits.
Since A * B are MAX_INT (usually 31 bits), you need a 64 bit number. You can use uint64_t

Dividing the integers in two separate arrays [duplicate]

This question already has answers here:
Array Division - What is the best way to divide two numbers stored in an array?
(7 answers)
Closed 9 years ago.
What I am trying to do is when given two arrays:
{1,5,1,7},
{4,1}
I want to get {3,7}. BTW, 1517 / 41 = 37
I can't think of simple algorithm to accomplish this. I can't simply convert the arrays into integers and use the regular division operator, because numbers in the arrays could be very huge that integers can't hold.
I've heard that using long division can help, but when I read it on Wikipedia, it only explains how to do math (http://en.wikipedia.org/wiki/Long_division). I know how to divide two numbers.
If you were to write some code, I'd prefer c++, but doesn't matter.
Any help will be appreciated.
If you use Python, this is easy.
f = lambda L: int(''.join(map(str,L)))
a = [1,5,1,7]
b = [4,1]
print map(int,str(f(a) / f(b))) # [3, 7]

Arbitrary precision arithmetic with GMP

I'm using the GMP library to make a Pi program, that will calculate about 7 trillion digits of Pi. Problem is, I can't figure out how many bits are needed to hold that many decimal places.
7 trillion digits can represent any of 10^(7 trillion) distinct numbers.
x bits can represent 2^x distinct numbers.
So you want to solve:
2^x = 10^7000000000000
Take the log-base-2 of both sides:
x = log2(10^7000000000000)
Recall that log(a^b) = b * log(a):
x = 7000000000000 * log2(10)
I get 23253496664212 bits. I would add one or two more just to be safe. Good luck finding the petabytes to hold them, though.
I suspect you are going to need a more interesting algorithm.
I wanna just correct one thing about what was written in the response answer:
Recall that log(a^b) = a * log(b)
well it is the opposite :
log(a^b) = b * log(a)
2^10 = 1024, so ten bits will represent slightly more than three digits. Since you're talking about 7 trillion digits, that would be something like 23 trillion bits, or about 3 terabytes, which is more than I could get on one drive from Costco last I visited.
You may be getting overambitious. I'd wonder about the I/O time to read and write entire disks for each operation.
(The mathematical way to solve it is to use logarithms, since a number that takes 7 trillion digits to represent has a log base 10 of about 7 trillion. Find the log of the number in the existing base, convert the base, and you've got your answer. For shorthand between base 2 and base 10, use ten bits==three digits, because that's not very far wrong. It says that the log base 10 of 2 is .3, when it's actually more like .301.)

multiplication of string [ containing integer], output also stored in string, How? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
Inputting large numbers in c++?
Arbitrary-precision arithmetic Explanation
I need to multiply two huge huge integers, like:
a=1212121212121212121212121212121212121212121212121212;
b=1212121212121212121212121212121212121212121212121212;
I think there are no data types in C and C++ to hold this huge an integer, so I thought to keep it as a string format like:-
char *number1="1212121212121212121212121212121212121212121212121212";
char *number2="1212121212121212121212121212121212121212121212121212";
during the time of multiplication I convert it into string with help of atoi() function like:
atoi(number1)*atoi(number2);
As usual the output of this multiplication will be obviously huge, so I need to change the output in string format.
I know there is an itoa() function which converts an integer to a string but it is not compatible with all compilers. Can any body tell me what I should do in this scenario?
I am using Ubuntu-10.04 and the g++ compiler.
Since C and C++ do not offer a native type that supports big numbers, it makes no sense to call atoi() to parse such numbers. atoi() returns a native int which is capped at 2,147,483,647 on 32-bit platforms.
You can use one of the numerous bignum libraries, like GMP for instance.
I think, the best variant besides using some math libraries is to split those numbers into int arrays with some fixed limit. Then just perform multiplication using basic math multiplication methods. And do not forget about overflows.
Multiplying the large numbers is very
difficult, however we can do it by
applying the logarithm of
multiplication of two numbers formula
and now we are going know how we
derived the product of two numbers’
logarithm.
Let us consider a, m and n are positive real numbers but a does not equal to 1 which means ‘a’ belongs to R+ – {1}. Logarithm of m and n to base a are x and y respectively by satisfying ax is equal to m and ay is equal to n condition.
loga (m.n) = x + y
As we already know x = loga m and y = loga n.
loga (m.n) = loga m + loga n
logarithm of multiplication of two values is equal to summation of the same values’ logarithms. The same logarithmic fundamental can now help us in multiplying the two large numbers by adding the logarithm of those values. If you don’t have a calculator, just take the logarithmic table help to perform this.
Using atoi() is also not helpful since the number itself won't fit in integer data type.
You have to simulate the method you did in elementary school.
121
*23
----
363
242*
----
2783
The implementation is left as an exercise. You would also need to know how to add big numbers.

φ(n) = (p-1)(q-1) p and q are two big numbers find e such that gcd(e,φ(n)) = 1 [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
φ(n) = (p-1)(q-1)
p and q are two big numbers
find e such that gcd(e,φ(n)) = 1
consider p and q to be a very large prime number (Bigint). I want to find a efficient solution for this.
[Edit] I can solve this using a brute force method. But as the numbers are too big I need more efficient solution.
also 1< e < (p-1)(q-1)
Usually you choose e to be a prime number. A common choice is 65537. You then select p and q so that gcd(p-1, e)=1 and gcd(q-1, e)=1, which just required you to check that p-1 and q-1 are not multiples of e (when you (rarely) find that one of them is, you generate a new prime instead).
65537 has the advantage of allowing you to optimize the public key operation by observing that x^65537 = x^(2^16+1) = x^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2^2 * x (mod m), so you just need 16 modular squarings and a modular multiplication.
You have to decide how big you want e to be. This is a system decision. Commonly, e used to be fixed at 3; more usual nowadays is e=65537. In these cases, e is prime, so (as others have already pointed out) you just have to check that (p-1)(q-1) is not a multiple of e.
But some system requirements specify a 32-bit random e. This is because some cryptographers feel that flaws are more likely to be discovered in fixed-exponent RSA systems than in random-exponent systems. (As far as I know, no concrete exploitation has been discovered for fixed-exponent systems; but cryptographers are paid to be over-cautious.)
So let's say you're stuck with having to generate a random 32-bit e that is co-prime to (p-1)(q-1). The simplest solution is this: Generate a random, odd 32-bit number e. Then calculate its inverse mod (p-1)(q-1). If this inverse calculation fails, because e is not co-prime to (p-1)(q-1), then try again.
This is a reasonable, practical solution. You will need to calculate the inverse anyway, and computing an inverse doesn't take much longer than computing a gcd.
If you really need to make it as fast as you can, you can look for small prime factors of (p-1)(q-1) and trial-divide e by these factors: if you find small prime factors, then you can speed up your search for e; if you don't, then the search will probably terminate quickly.
Another reasonable soltuion is to generate a random 32-bit prime e, and check (p-1)(q-1) for divisibility by e. Whether this is allowed would depend on your system requirements. Are you setting these system requirements yourself?
Pick first prime number >= 3 that satisfies this.
If you are looking for speed, you might use small exponent.
There might be two problems whit 2 exponents.
You should not use small exponents to encrypt same massage whit multiple schemes. (for instance if there are tree private/public pairs whit exp = 3 you can use Gauss’s algorithm to recover plaintext.
You should not send short messages because attacker might use only cube root to recover this.
Considering these weaknesses you might use this scheme. And as far as I know number 3 is common number for e.
By the way, brute forcing few numbers is negligible compared to checking for primality.
I think you may have misstated the problem; e=1 works nicely for the one you've written.
What you need to do then is compute de = 1 mod phi(n). This is actually very quick - you simply need to use the extended Euclidean Algorithm on e and phi n. Doing so will allow you to compute de + k\phi(n) = 1 which is to say you have computed the inverse of e under \phi(n).
Edit, Rasmus Faber is correct, you do need to verify that gcd(e, \phi(n)) = 1. The extended Euclidean Algorithm will still do this for you - you compute both the gcd and the multiples of e, phi(n). This tells you what d is, namely that d is the inverse of e, modulu phi n which tells you that t^ed = t^1 modulo phi n.
As for doing this in practice, well, I strongly suggest using a bignum library; rolling your own arbitrary precision euclidean extended algorithm isn't easy. Here is one such function that will do this efficiently for arbitrary precision arithmetic.