I try Montgomery Multiplication Algorithm on Python 3.x. This algorithm pseudo-code is given below:
Input: Modulus N(n bit), gcd(n, 2) = 1, Multipler: A (n bit), Multiplicant: B (n bit)
Output: R = (A x B x 2 ^ (-n)) mod N
R = 0
for (i = 0; i < n; i++)
{
q = (R + A(i) * B) mod 2
R = (R + A(i) * B + q * N) / 2
}
print(R)
Python 3.x code that was written is given below:
#!/usr/bin/python3
N = 41
A = 13
B = 17
n = N.bit_length()
R = 0
for i in range(0, n):
q = int(R + (A & (1 << i) != 0) * B) % 2
R = int((R + (A & (1 << i) != 0) * B + q * N) / 2)
print("Result:", R % N)
But, the code isn't given correct result. What is the problem?
Thanks for answering.
When I run your (modified) code I get 31, and 31 appears to be the right answer.
According to your pseudocode, R should be
R = (A x B x 2 ^ (-n)) mod N
In your case that is
R = (13*17*2^(-6))%41
The interpretation of 2^(-6) when you are working mod 41 is to raise the mod 41 multiplicative inverse of 2 to the power 6, then take the result mod 41. In other words, 2^-6 = (2^-1)^6.
Since 2*21 = 42 = 1 (mod 41), 2^(-1) = 21 (mod 41). Thus:
R = (13*17*2^-6) (mod 41)
= (13*17*(2^-1)^6) (mod 41)
= (13*14*21^6) (mod 41)
= 18954312741 (mod 41)
= 31
which shows that the result is 31, the number returned by your code.
Thus your code is correct. If there is a clash between output and expectation, perhaps in this case the problem is one of expectation.
Related
So I have tried the same math in c# and python but got 2 different answer. can someone please explain why is this happening.
def test():
l = 50
r = 3
gg= l + (r - l) / 2
mid = l + (r - l) // 2
print(mid)
print(gg)
public void test()
{
var l = 50;
var r = 3;
var gg = l + (r - l) / 2;
double x = l + (r - l) / 2;
var mid = Math.Floor(x);
Console.WriteLine(mid);
Console.WriteLine(gg);
}
In C#, the / operator performs integer division (ignores the fractional part) when both values are type int. For example, 3 / 2 = 1, since the fractional part (0.5) is dropped.
As a result, in your equation, the operation (r - l) / 2 is evaluating to -23, since (3 - 50) / 2 = -47 / 2 = -23 (again, the fractional part is dropped). Then, 50 + (-23) = 27.
However, Python does not do this. By default, all division, whether between integers or doubles, is "normal" division - the fractional part is kept. Because of that, the result is the same as you'd get on a calculator: 50 + (3 - 50) / 2 = 26.5
If you want C# to calculate this the same way as Python, the easiest way is to make one of the numbers a double. Adding .0 to the end of the divisor should do the trick:
// changed '2' to '2.0'
var gg = l + (r - l) / 2.0;
double x = l + (r - l) / 2.0;
26
26.5
import sys
t=(int(sys.stdin.readline()))
for i in range(0,t):
n=int(sys.stdin.readline())
c=0
s=n*(n+1)/2
if s%2!=0:
print(0)
else:
c=0
i=-1
a=[i for i in range(1,n+1)]
h=s//2
m=0
s1=0
for i in range(n-1,-1,-1):
s1+=a[i]
c+=1
if s1==h:
m=1
break
if s1>h:
break
if m==1:
s1=((c+1)*(2+((c-1)-1)))//2+((n-c-1)*(2+((n-c-1)-1)))//2
print(s1)
else:
print(c)
I am new to python , How can i write this code with using for loop? i don't want to use for loop because i get TLE error. Thanks in advance
Here is the question :
N. Consider the sequence sequence=(1,2,…,N). You should choose two elements of this sequence and swap them.
A swap is perfect if there is an integer o (1≤o<N) such that the sum of the first M elements of the resulting sequence is equal to the sum of its last N−o elements. Find the number of perfect swaps.
i got interested in the problem and found this so far:
a slow version that creates list and really does swap elements is this:
from itertools import combinations
def slow(N):
found = 0
for i, j in combinations(range(N), 2):
lst = list(range(1, N + 1))
lst[i], lst[j] = lst[j], lst[i]
for m in range(1, N):
a = m * (m + 1) // 2
b = (N - m) * (N + m + 1) // 2
if i < m <= j:
a = a - i + j
b = b - j + i
assert a == sum(lst[:m])
assert b == sum(lst[m:])
if sum(lst[:m]) == sum(lst[m:]):
found += 1
if i < m <= j:
assert 2 * m * (m + 1) + 4 * j == N * (N + 1) + 4 * i
else:
assert 2 * m * (m + 1) == N * (N + 1)
else:
if i < m <= j:
assert 2 * m * (m + 1) + 4 * j != N * (N + 1) + 4 * i
else:
assert 2 * m * (m + 1) != N * (N + 1)
return found
as you see i found criteria the indices have to fulfill in order for the sum to be correct:
if i < m <= j:
assert 2 * m * (m + 1) + 4 * j == N * (N + 1) + 4 * i
else:
assert 2 * m * (m + 1) == N * (N + 1)
i also found the direct formula to calculate the sum up to m and the one starting from m:
a = m * (m + 1) // 2
b = (N - m) * (N + m + 1) // 2
if i < m <= j:
a = a - i + j
b = b - j + i
all of that can can be calculated using some basic mathematics.
starting from that you can do some more maths and see that there are 2 cases to consider:
there is an m such that the sum of the original list [1, 2, 3, ..., m, m+1, ..., N] up to m equals the sum of the rest of the list (e.g. N = 20; m = 14). two cases again:
all the swaps that do not cross the m boundary are valid (there are comb(m, 2) + comb((N - m), 2)) of them.
when you split at m-1 you will find more swaps; this time you have to swap accross the m-1 boundary.
the m in that case is calculated from
m = - 1 + sqrt(1 + 2 * N * (N + 1)) / 2
the calculation for m in the first case is not an integer (i.e. 1 + 2 * N * (N + 1) is not a perfect square). the m to consider is then then the floor of the result of the formula above (i use int instead of math.floor). two cases again for the difference of the sum of the two splits:
the difference is even: there are more swaps that need to go over the m boundary.
the difference is odd: no additional swaps (swapping will always result in an even difference)
this is the code:
from math import sqrt, comb
def fast(N):
found = 0
arg = (1 + 2 * N * (N + 1))
sq = round(sqrt(arg))
if sq ** 2 == arg and sq & 1:
m = (-1 + sq) // 2
found += comb(m, 2) + comb((N - m), 2)
m -= 1
found += N - m - 1
else:
m = int((-1 + sqrt(arg)) // 2)
diff = ((m + 1 + N) * (N - m) - m * (m + 1)) // 2
if diff & 1 == 0:
found += N - m
return found
Attempting to convert this EGCD equation into python.
egcd(a, b) = (1, 0), if b = 0
= (t, s - q * t), otherwise, where
q = a / b (note: integer division)
r = a mod b
(s, t) = egcd(b, r)
The test I used was egcd(5, 37) which should return (15,-2) but is returning (19.5, -5.135135135135135)
My code is:
def egcd(a, b):
if b == 0:
return (1, 0)
else:
q = a / b # Calculate q
r = a % b # Calculate r
(s,t) = egcd(b,r) # Calculate (s, t) by calling egcd(b, r)
return (t,s-q*t) # Return (t, s-q*t)
a / b in Python 3 is "true division" the result is non-truncating floating point division even when both operands are ints.
To fix, either use // instead (which is floor division):
q = a // b
or use divmod to perform both division and remainder as a single computation, replacing both of these lines:
q = a / b
r = a % b
with just:
q, r = divmod(a, b)
Change q = a / b for q = a // b
Here is an link to spoj problem http://www.spoj.com/problems/GOODB/.
you are given N, WA, TLE, RE such that
N = WA+TLE+RE
how many different ordered combinations of N incorrect results (each being WA, TLE, or RE) exist which satisfy their predictions?
and here is my working solution in python
import math
mod=10**9+7
def nck(n,k):
return math.factorial(n)/(math.factorial(n-k) * math.factorial(k))
n,w,t,r = map(int, raw_input().split())
print (nck(n,w) * nck(n-w, t)) % mod
Here is second approach for the same problem by the assumption that the number of ways to arrange
n1 a1 's, n2 a2 's, …, nk ak 's in a row is
n!/(n1! n2! .... nk !)
, where
n = n1 + n2 +...+ nk
here is the code for my second approach
def modexp(x, y, mod):
res = 1
if x==0 or x==1:
return 1
while y != 0:
if y & 1 == 1:
'if y is odd'
res = (res * x) % mod
x = (x * x) % mod
y >>= 1
return res
def modfact(n, mod):
res = 1
while n >= 1:
res = (res * n) % mod
n -= 1
return res
mod = 10 ** 9 + 7
n, w, t, r = map(int, input().split())
resn = modfact(n, mod)
resw = modexp(modfact(w, mod), mod - 2, mod)
rest = modexp(modfact(t, mod), mod - 2, mod)
resr = modexp(modfact(r, mod), mod - 2, mod)
res = (resn*resw*rest*resr)%mod
print(res)
I just can't figure out why my second approach is wrong.Can someone provide any insights where i am going wrong.
This line is suspicious:
res = resn//(resw*rest*resr)
resw and friends are modular inverses of the factorials, so they should be multiplied instead of divided. The final result should be modded out by 10**9 + 7.
I am trying to solve this problem in Python. Noting that only the first kiss requires the alternation, any kiss that is not a part of the chain due to the first kiss can very well have a hug on the 2nd next person, this is the code I have come up with. This is just a simple mathematical calculation, no looping, no iteration, nothing. But still I am getting a timed-out message. Any means to optimize it?
import psyco
psyco.full()
testcase = int(raw_input())
for i in xrange(0,testcase):
n = int(raw_input())
if n%2:
m = n/2;
ans = 2 + 4*(2**m-1);
ans = ans%1000000007;
print ans
else:
m = n/2 - 1
ans = 2 + 2**(n/2) + 4*(2**m-1);
ans = ans%1000000007
print ans
You're computing powers with very large exponents, which is extremely slow if the results are not reduced in process. For example, a naive computation of 10**10000000 % 11 requires creating a 10000000-digit number and taking modulo 11. A better way is modular exponentiation where you reduce modulo 11 after each multiplication and the integer never gets larger.
Python provides built-in modular exponentiation. Use pow(a,b,c) to compute (a**b) % c.
This is under assumption that your algorithm is correct, which I did not verify.
The answer to this is a pretty simple recursion. F(1) = 2 and for F(n) we have two choices:
n = H, then the number of ways to kiss the remaining guests is simply F(n-1)
n = K, then the number of ways to kiss the remaining guests is 2 ** k where k is the number of remaining guests that the princess is not forced to kiss. Since she has to kiss every second remaining guest, k = ceil((n - 1) / 2)
Putting them together, we get F(n) = F(n - 1) + 2 ** ceil((n - 1) / 2)
My attempt, including taking everything mod 1000000007:
from math import ceil
def F(n):
m = 1000000007
a = 2
for i in range(2, n+1):
a = (a + pow(2, int(ceil((i - 1.0) / 2)), m)) % m
return a
EDIT: Updated (much faster and more unreadable! F(1e9) takes about 3 minutes):
def F(n):
m = 1000000007
a = 2
z = 1
for i in xrange(2, n, 2):
z = (z * 2) % m
a = (a + z + z) % m
if (n & 1 == 0):
z = (z * 2) % m
a = (a + z) % m
return a
EDIT 2: After further thought, I realised the above is actually just:
F(n) = (1 + 1) + (2 + 2) + (4 + 4) + ... + (2 ** n/2 + 2 ** n/2)
= 2 * (1 + 2 + 4 + ... + 2 ** n/2)
= 2 * (2 ** (n/2 + 1) - 1)
= 2 ** (n/2 + 2) - 2
But if n is even, the last 2 ** n/2 only occurs once, so we have:
def F(n):
m = 1000000007
z = pow(2, n/2, m)
if (n % 2 == 0):
return (z * 3 - 2) % m
else:
return (z * 4 - 2) % m
Which runs much faster! (Limited by the speed of pow(x, y, z), which I think is O(lg n)?)
And just because, here is the one-liner:
def F(n):
return (pow(2, n/2, 1000000007) * (3 + n % 2) - 2) % 1000000007
Results:
1 => 2
2 => 4
3 => 6
4 => 10
5 => 14
6 => 22
7 => 30
8 => 46
9 => 62
10 => 94
1e6 => 902893650
1e7 => 502879941
1e8 => 251151906
1e9 => 375000001