C# and Python result difference - basic Math - python

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

Related

Difference in n = (n * (n + 1)) // 2 and n = (n * (n + 1)) / 2; n = int(n)

I am new to competitive programming and python. I was trying this question on codechef, https://www.codechef.com/CCSTART2/problems/ADDNATRL which requires me to find the sum of first N natural numbers.
this was my first solution:
n = int(input())
n = (n * (n + 1)) / 2
print(int(n))
This gave me a Wrong Answer [WA].
While the below solution was Accepted,
n = int(input())
n = (n * (n + 1)) // 2
print(n)
so I was wondering what the actual difference is since both gave me the same output in my local machine.
/ gives the quotient as a float while // gives integer result.
At the upper end of the range for n, 1e9, the intermediate result of around 1e18 cannot be represented exactly in an IEEE "double" float, which is what python usually uses, and suffers rounding error. An approximate answer is output.
Meanwhile the range for integers is unlimited, so the exact answer is output.
For example:
>>> n = 999999998
>>> int((n * (n + 1)) / 2)
499999998500000000
>>> (n * (n + 1)) // 2
499999998500000001
>>>
/ gives the remainder in float while // gives integer result.
// is same as the / in other programming or scripting languages.
But in Python / is introduced as division that gives a integer output and // is floor division that gives integer output
As in competitive programming, the best way is taken. You can use // other than using / and int(). This reduces running time also

Auto Round Off in Python3

I wrote a code for finding the 'j' for the General Annuity
from __future__ import division
R = float(38973.76)
n = int(3)
r = int(8)
m = int(4)
mSubj = int(1)
t = int(3)
ans = ((1 + r / m) ** m)**(1 / mSubj) - 1
print(ans)
now the answer is 80.0
instead of 0.008243216 that I solved in Scientific Calculator.
Your R variable is the capital one, not r.
so it should be ans = ((1 + R / m) ** m)**(1 / mSubj) - 1

Volume of pile of cubes

I'm trying a challenge. The idea is the following:
"Your task is to construct a building which will be a pile of n cubes.
The cube at the bottom will have a volume of n^3, the cube above will
have volume of (n-1)^3 and so on until the top which will have a
volume of 1^3.
You are given the total volume m of the building. Being given m can
you find the number n of cubes you will have to build? If no such n
exists return -1"
I saw that apparently:
2³ + 1 = 9 = 3² and 3 - 1 = 2
3³ + 2³ + 1 = 36 = 6² and 6 - 3 = 3
4³ + 3³ + 2³ + 1 = 100 = 10² and 10 - 6 = 4
5³ + 4³ + 3³ + 2³ + 1 = 225 = 15² and 15 - 10 = 5
6³ + 5³ + 4³ + 3³ + 2³ + 1 = 441 = 21² and 21 - 15 = 6
So if I thought, if I check that a certain number is a square root I can already exclude a few. Then I can start a variable at 1 at take that value (incrementing it) from the square root. The values will eventually match or the former square root will become negative.
So I wrote this code:
def find_nb(m):
x = m**0.5
if (x%1==0):
c = 1
while (x != c and x > 0):
x = x - c
c = c + 1
if (x == c):
return c
else:
return -1
return -1
Shouldn't this work? What am I missing?
I fail a third of the sample set, per example: 10170290665425347857 should be -1 and in my program it gives 79863.
Am I missing something obvious?
You're running up against a floating point precision problem. Namely, we have
In [101]: (10170290665425347857)**0.5
Out[101]: 3189089316.0
In [102]: ((10170290665425347857)**0.5) % 1
Out[102]: 0.0
and so the inner branch is taken, even though it's not actually a square:
In [103]: int((10170290665425347857)**0.5)**2
Out[103]: 10170290665425347856
If you borrow one of the many integer square root options from this question and verify that the sqrt squared gives the original number, you should be okay with your algorithm, at least if I haven't overlooked some corner case.
(Aside: you've already noticed the critical pattern. The numbers 1, 3, 6, 10, 15.. are quite famous and have a formula of their own, which you could use to solve for whether there is such a number that works directly.)
DSM's answer is the one, but to add my two cents to improve the solution...
This expression from Brilliant.org is for summing cube numbers:
sum of k**3 from k=1 to n:
n**2 * (n+1)**2 / 4
This can of course be solved for the total volume in question. This here is one of the four solutions (requiring both n and v to be positive):
from math import sqrt
def n(v):
return 1/2*(sqrt(8*sqrt(v) + 1) - 1)
But this function also returns 79863.0. Now, if we sum all the cube numbers from 1 to n, we get a slightly different result due to the precision error:
v = 10170290665425347857
cubes = n(v) # 79863
x = sum([i**3 for i in range(cubes+1)])
# x = 10170290665425347857, original
x -> 10170290665425347856
I don't know if your answer is correct, but I have another solution to this problem which is waaaay easier
def max_level(remain_volume, currLevel):
if remain_volume < currLevel ** 3:
return -1
if remain_volume == currLevel ** 3:
return currLevel
return max_level(remain_volume - currLevel**3, currLevel + 1)
And you find out the answer with max_level(m, 0). It takes O(n) time and O(1) memory.
I have found a simple solution over this in PHP as per my requirement.
function findNb($m) {
$total = 0;
$n = 0;
while($total < $m) {
$n += 1;
$total += $n ** 3;
}
return $total === $m ? $n : -1;
}
In Python it would be:
def find_nb(m):
total = 0
n = 0
while (total < m):
n = n + 1
total = total + n ** 3
return n if total == m else -1

Montgomery Multiplication Algorithm on Python

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.

Any better algorithm possible here?

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

Categories