I need compute (9173501*9173502*9173504)%9173503 in C#; - c#

I need compute (9173501 * 9173502 * 9173504) % 9173503 in C#; result = 2 but C# can't compute it.
If you have any idea please help me.

There is no need to use big integers.
Use this formula:
(x * y) % k = ((x % k) * (y % k)) % k
This way, you can apply the modulo to a product of two numbers, each of which will be < 9173503, so this product will fit in a long.
Note: the same holds true for addition:
(x + y) % k = ((x % k) + (y % k)) % k
And subtraction, with a slight change:
(x - y) % k = ((((x % k + k) % k) - ((y % k + k) % k)) % k + k) % k
It does not, however, hold for division:
(4 / 2) % 3 = 2
4 mod 3 = 1
2 mod 3 = 2
1 / 2 != 2

Convert your number to a BigInteger before you begin computations:
Console.WriteLine((new BigInteger(9173501)*9173502*9173504)%9173503);
// Output: 2

You can't directly compute it without BigInteger, but mathematically it's equivalent to:
((long)9173501 % 9173503) * (9173502 % 9173503) * (9173504 % 9173503) % 9173503

This is a math question, not a programming one.
As you see the numbers are really close to each other, so substituting n = 9173503 you will get: (n-2)(n-1)(n+1) % n.
Opening up the parenthesis you will get the following polynomial: n^3 - 2*n^2 - n + 2 and the remainder by n will be:
2 for every n > 2
0 for n = 1, 2
This means that not only (9173501 * 9173502 * 9173504) % 9173503 = 2, but also 13^127^61 * (13^127^61 + 1) * (13^127^61 + 3) % (13^127^61 + 2) is also 2, which is most probably can not be calculated with C# or other programming languages.

Related

What is the workflow of Pow(x,y) function?

I'm going through "sololearn" and udemy courses to try to learn C#. I am doing the challenges but could not figure out how the below code resulted with 32 (as in 32 is the correct answer here and I am trying to find out why). Can someone explain this process to me, the method calling itself is throwing me I think.
static double Pow(double x, int y)
{
if (y == 0)
{
return 1.0;
}
else
{
return x * Pow(x, y - 1);
}
}
static void Main()
{
Console.Write(Pow(2, 5));
}
Please excuse my bad coding. I am trying to do it on mobile, which is difficult, the answer was 32. Can someone explain why?
Edit: Aplogies here is how I work through it. Pass 2 and 5 to Pow, check if y == 0 which is false, it is now y == 5 so x * pow(x, y-1) formula will be active. X is still 2, y is now 4 which means it fails the check again on whether it equals 0, this loop continues until it returns the 1.0, x has remained at 2 so 2 * 1.0 = 2 and not 32?
First thing to note is that this is NOT how you would normally implement a power function. It's done this way to demonstrate recursion.
With that out the way, let's look at what happens when you call Pow(2, 5):
Pow(x = 2, y = 5)
-> return 2 * Pow(2, 4)
<- 2 * 16 = 32
Pow(x = 2, y = 4)
-> return 2 * Pow(2, 3)
<- 2 * 8 = 16
Pow(x = 2, y = 3)
-> return 2 * Pow(2, 2)
<- 2 * 4 = 8
Pow(x = 2, y = 2)
-> return 2 * Pow(2, 1)
<- 2 * 2 = 4
Pow(x = 2, y = 1)
-> return 2 * Pow(2, 0)
<- 2 * 1 = 2
Pow(x = 2, y = 0)
-> return 1 (because y == 0)
<- 1
To read this representation of the recursive call stack, work your way from the top to the bottom looking at how the arguments change; then work your way back up from the bottom to the top looking at the return values (which I indicate with <-).
Ok so let's go through the whole thing.
First of all, a static function is one that can be called without need to instantiate an object. There is one signature that all objects of the same class share. The double is a type within C# and its appearing here to show what the final output type of the function will be. Pow is the name of the function, double x, int y are parameters described by their type (not very well named but we'll leave that for another day)
So x is a number and y is the power of that number. There is a conditional here to check for two outcomes. If y is 0 then the answer is always 1, simple maths. Otherwise, the function performs the arithmetic using recursion (it calls itself again until it meets a terminating condition). The reason we get 32 is because 2x2x2x2x2 = 32. It is 2 to the power of 5.
I'm presuming you know what main and console.write are.
That method basically computes "x raised to the power of y". It does this in a recursive manner.
First, it defines a base case: anything raised to the power of 0 is 1.
Then, it defines what to do in all other cases: x * Pow(x, y - 1). Assuming y is big, what's x * Pow(x, y - 1)? It's x * x * Pow(x, y - 2), which in turn is x * x * x * Pow(x, y - 3). See the pattern here? Eventually, you will reach the point where the second argument, y - N, is 0, which as we have established, is 1. At that point, how many x * have we got? Exactly y.
Let's see this in action for Pow(2, 5):
Pow(2, 5)
2 * Pow(2, 4)
2 * 2 * Pow(2, 3)
2 * 2 * 2 * Pow(2, 2)
2 * 2 * 2 * 2 * Pow(2, 1)
2 * 2 * 2 * 2 * 2 * Pow(2, 0)
2 * 2 * 2 * 2 * 2 * 1
Hence the result 32.
Hello its recursion and it repeat until y=1, then return 2,then return 4, 8, 16, 32 at then end. 2^5=32
To be able to understand each action in this recursive behavior log all the details to see what is actually going on. Such as :
using System;
namespace Tester
{
class test
{
// What Pow actually does:
static double logPow(double x, int y) {
var old = x; // Hold the x
for (var i = 0; i < y; i++){ // do it y times
x = old * x; // Multiply with it's first self
}
return x;
}
static int counter = 0;
static double Pow(double x, int y) {
counter++;
Console.Write("Recursive action[" + counter + "] Y status ["+ y +"] : ");
if (y == 0)
{
Console.Write("return 1.0 = " + logPow(x, y) + " \n");
return 1.0;
}
else
{
Console.Write("return " + x + " * Pow(" + x + ", " + y + " - 1) = " + logPow(x,y-1) + " \n");
return x * Pow(x, y - 1);
}
}
static void Main() {
Console.Write("Last Result : " + Pow(2, 5));
}
}
}
Which gives the result :
Recursive action[1] Y status [5] : return 2 * Pow(2, 5 - 1) = 32
Recursive action[2] Y status [4] : return 2 * Pow(2, 4 - 1) = 16
Recursive action[3] Y status [3] : return 2 * Pow(2, 3 - 1) = 8
Recursive action[4] Y status [2] : return 2 * Pow(2, 2 - 1) = 4
Recursive action[5] Y status [1] : return 2 * Pow(2, 1 - 1) = 2
Recursive action[6] Y status [0] : return 1.0 = 2
Last Result : 32
You can debug your code by looking at these details.
Also you can have fun with it using this link : https://onlinegdb.com/Bysbxat9H

How to enumerate x^2 + y^2 = z^2 - 1 (with additional constraints)

Lets N be a number (10<=N<=10^5).
I have to break it into 3 numbers (x,y,z) such that it validates the following conditions.
1. x<=y<=z
2. x^2+y^2=z^2-1;
3. x+y+z<=N
I have to find how many combinations I can get from the given numbers in a method.
I have tried as follows but it's taking so much time for a higher number and resulting in a timeout..
int N= Int32.Parse(Console.ReadLine());
List<String> res = new List<string>();
//x<=y<=z
int mxSqrt = N - 2;
int a = 0, b = 0;
for (int z = 1; z <= mxSqrt; z++)
{
a = z * z;
for (int y = 1; y <= z; y++)
{
b = y * y;
for (int x = 1; x <= y; x++)
{
int x1 = b + x * x;
int y1 = a - 1;
if (x1 == y1 && ((x + y + z) <= N))
{
res.Add(x + "," + y + "," + z);
}
}
}
}
Console.WriteLine(res.Count());
My question:
My solution is taking time for a bigger number (I think it's the
for loops), how can I improve it?
Is there any better approach for the same?
Here's a method that enumerates the triples, rather than exhaustively testing for them, using number theory as described here: https://mathoverflow.net/questions/29644/enumerating-ways-to-decompose-an-integer-into-the-sum-of-two-squares
Since the math took me a while to comprehend and a while to implement (gathering some code that's credited above it), and since I don't feel much of an authority on the subject, I'll leave it for the reader to research. This is based on expressing numbers as Gaussian integer conjugates. (a + bi)*(a - bi) = a^2 + b^2. We first factor the number, z^2 - 1, into primes, decompose the primes into Gaussian conjugates and find different expressions that we expand and simplify to get a + bi, which can be then raised, a^2 + b^2.
A perk of reading about the Sum of Squares Function is discovering that we can rule out any candidate z^2 - 1 that contains a prime of form 4k + 3 with an odd power. Using that check alone, I was able to reduce Prune's loop on 10^5 from 214 seconds to 19 seconds (on repl.it) using the Rosetta prime factoring code below.
The implementation here is just a demonstration. It does not have handling or optimisation for limiting x and y. Rather, it just enumerates as it goes. Play with it here.
Python code:
# https://math.stackexchange.com/questions/5877/efficiently-finding-two-squares-which-sum-to-a-prime
def mods(a, n):
if n <= 0:
return "negative modulus"
a = a % n
if (2 * a > n):
a -= n
return a
def powmods(a, r, n):
out = 1
while r > 0:
if (r % 2) == 1:
r -= 1
out = mods(out * a, n)
r /= 2
a = mods(a * a, n)
return out
def quos(a, n):
if n <= 0:
return "negative modulus"
return (a - mods(a, n))/n
def grem(w, z):
# remainder in Gaussian integers when dividing w by z
(w0, w1) = w
(z0, z1) = z
n = z0 * z0 + z1 * z1
if n == 0:
return "division by zero"
u0 = quos(w0 * z0 + w1 * z1, n)
u1 = quos(w1 * z0 - w0 * z1, n)
return(w0 - z0 * u0 + z1 * u1,
w1 - z0 * u1 - z1 * u0)
def ggcd(w, z):
while z != (0,0):
w, z = z, grem(w, z)
return w
def root4(p):
# 4th root of 1 modulo p
if p <= 1:
return "too small"
if (p % 4) != 1:
return "not congruent to 1"
k = p/4
j = 2
while True:
a = powmods(j, k, p)
b = mods(a * a, p)
if b == -1:
return a
if b != 1:
return "not prime"
j += 1
def sq2(p):
if p % 4 != 1:
return "not congruent to 1 modulo 4"
a = root4(p)
return ggcd((p,0),(a,1))
# https://rosettacode.org/wiki/Prime_decomposition#Python:_Using_floating_point
from math import floor, sqrt
def fac(n):
step = lambda x: 1 + (x<<2) - ((x>>1)<<1)
maxq = long(floor(sqrt(n)))
d = 1
q = n % 2 == 0 and 2 or 3
while q <= maxq and n % q != 0:
q = step(d)
d += 1
return q <= maxq and [q] + fac(n//q) or [n]
# My code...
# An answer for https://stackoverflow.com/questions/54110614/
from collections import Counter
from itertools import product
from sympy import I, expand, Add
def valid(ps):
for (p, e) in ps.items():
if (p % 4 == 3) and (e & 1):
return False
return True
def get_sq2(p, e):
if p == 2:
if e & 1:
return [2**(e / 2), 2**(e / 2)]
else:
return [2**(e / 2), 0]
elif p % 4 == 3:
return [p, 0]
else:
a,b = sq2(p)
return [abs(a), abs(b)]
def get_terms(cs, e):
if e == 1:
return [Add(cs[0], cs[1] * I)]
res = [Add(cs[0], cs[1] * I)**e]
for t in xrange(1, e / 2 + 1):
res.append(
Add(cs[0] + cs[1]*I)**(e-t) * Add(cs[0] - cs[1]*I)**t)
return res
def get_lists(ps):
items = ps.items()
lists = []
for (p, e) in items:
if p == 2:
a,b = get_sq2(2, e)
lists.append([Add(a, b*I)])
elif p % 4 == 3:
a,b = get_sq2(p, e)
lists.append([Add(a, b*I)**(e / 2)])
else:
lists.append(get_terms(get_sq2(p, e), e))
return lists
def f(n):
for z in xrange(2, n / 2):
zz = (z + 1) * (z - 1)
ps = Counter(fac(zz))
is_valid = valid(ps)
if is_valid:
print "valid (does not contain a prime of form\n4k + 3 with an odd power)"
print "z: %s, primes: %s" % (z, dict(ps))
lists = get_lists(ps)
cartesian = product(*lists)
for element in cartesian:
print "prime square decomposition: %s" % list(element)
p = 1
for item in element:
p *= item
print "complex conjugates: %s" % p
vals = p.expand(complex=True, evaluate=True).as_coefficients_dict().values()
x, y = vals[0], vals[1] if len(vals) > 1 else 0
print "x, y, z: %s, %s, %s" % (x, y, z)
print "x^2 + y^2, z^2-1: %s, %s" % (x**2 + y**2, z**2 - 1)
print ''
if __name__ == "__main__":
print f(100)
Output:
valid (does not contain a prime of form
4k + 3 with an odd power)
z: 3, primes: {2: 3}
prime square decomposition: [2 + 2*I]
complex conjugates: 2 + 2*I
x, y, z: 2, 2, 3
x^2 + y^2, z^2-1: 8, 8
valid (does not contain a prime of form
4k + 3 with an odd power)
z: 9, primes: {2: 4, 5: 1}
prime square decomposition: [4, 2 + I]
complex conjugates: 8 + 4*I
x, y, z: 8, 4, 9
x^2 + y^2, z^2-1: 80, 80
valid (does not contain a prime of form
4k + 3 with an odd power)
z: 17, primes: {2: 5, 3: 2}
prime square decomposition: [4 + 4*I, 3]
complex conjugates: 12 + 12*I
x, y, z: 12, 12, 17
x^2 + y^2, z^2-1: 288, 288
valid (does not contain a prime of form
4k + 3 with an odd power)
z: 19, primes: {2: 3, 3: 2, 5: 1}
prime square decomposition: [2 + 2*I, 3, 2 + I]
complex conjugates: (2 + I)*(6 + 6*I)
x, y, z: 6, 18, 19
x^2 + y^2, z^2-1: 360, 360
valid (does not contain a prime of form
4k + 3 with an odd power)
z: 33, primes: {17: 1, 2: 6}
prime square decomposition: [4 + I, 8]
complex conjugates: 32 + 8*I
x, y, z: 32, 8, 33
x^2 + y^2, z^2-1: 1088, 1088
valid (does not contain a prime of form
4k + 3 with an odd power)
z: 35, primes: {17: 1, 2: 3, 3: 2}
prime square decomposition: [4 + I, 2 + 2*I, 3]
complex conjugates: 3*(2 + 2*I)*(4 + I)
x, y, z: 18, 30, 35
x^2 + y^2, z^2-1: 1224, 1224
Here is a simple improvement in Python (converting to the faster equivalent in C-based code is left as an exercise for the reader). To get accurate timing for the computation, I removed printing the solutions themselves (after validating them in a previous run).
Use an outer loop for one free variable (I chose z), constrained only by its relation to N.
Use an inner loop (I chose y) constrained by the outer loop index.
The third variable is directly computed per requirement 2.
Timing results:
-------------------- 10
1 solutions found in 2.3365020751953125e-05 sec.
-------------------- 100
6 solutions found in 0.00040078163146972656 sec.
-------------------- 1000
55 solutions found in 0.030081748962402344 sec.
-------------------- 10000
543 solutions found in 2.2078349590301514 sec.
-------------------- 100000
5512 solutions found in 214.93411707878113 sec.
That's 3:35 for the large case, plus your time to collate and/or print the results.
If you need faster code (this is still pretty brute-force), look into Diophantine equations and parameterizations to generate (y, x) pairs, given the target value of z^2 - 1.
import math
import time
def break3(N):
"""
10 <= N <= 10^5
return x, y, z triples such that:
x <= y <= z
x^2 + y^2 = z^2 - 1
x + y + z <= N
"""
"""
Observations:
z <= x + y
z < N/2
"""
count = 0
z_limit = N // 2
for z in range(3, z_limit):
# Since y >= x, there's a lower bound on y
target = z*z - 1
ymin = int(math.sqrt(target/2))
for y in range(ymin, z):
# Given y and z, compute x.
# That's a solution iff x is integer.
x_target = target - y*y
x = int(math.sqrt(x_target))
if x*x == x_target and x+y+z <= N:
# print("solution", x, y, z)
count += 1
return count
test = [10, 100, 1000, 10**4, 10**5]
border = "-"*20
for case in test:
print(border, case)
start = time.time()
print(break3(case), "solutions found in", time.time() - start, "sec.")
The bounds of x and y are an important part of the problem. I personally went with this Wolfram Alpha query and checked the exact forms of the variables.
Thanks to #Bleep-Bloop and comments, a very elegant bound optimization was found, which is x < n and x <= y < n - x. The results are the same and the times are nearly identical.
Also, since the only possible values for x and y are positive even integers, we can reduce the amount of loop iterations by half.
To optimize even further, since we compute the upper bound of x, we build a list of all possible values for x and make the computation parallel. That saves a massive amount of time on higher values of N but it's a bit slower for smaller values because of the overhead of the parallelization.
Here's the final code:
Non-parallel version, with int values:
List<string> res = new List<string>();
int n2 = n * n;
double maxX = 0.5 * (2.0 * n - Math.Sqrt(2) * Math.Sqrt(n2 + 1));
for (int x = 2; x < maxX; x += 2)
{
int maxY = (int)Math.Floor((n2 - 2.0 * n * x - 1.0) / (2.0 * n - 2.0 * x));
for (int y = x; y <= maxY; y += 2)
{
int z2 = x * x + y * y + 1;
int z = (int)Math.Sqrt(z2);
if (z * z == z2 && x + y + z <= n)
res.Add(x + "," + y + "," + z);
}
}
Parallel version, with long values:
using System.Linq;
...
// Use ConcurrentBag for thread safety
ConcurrentBag<string> res = new ConcurrentBag<string>();
long n2 = n * n;
double maxX = 0.5 * (2.0 * n - Math.Sqrt(2) * Math.Sqrt(n2 + 1L));
// Build list to parallelize
int nbX = Convert.ToInt32(maxX);
List<int> xList = new List<int>();
for (int x = 2; x < maxX; x += 2)
xList.Add(x);
Parallel.ForEach(xList, x =>
{
int maxY = (int)Math.Floor((n2 - 2.0 * n * x - 1.0) / (2.0 * n - 2.0 * x));
for (long y = x; y <= maxY; y += 2)
{
long z2 = x * x + y * y + 1L;
long z = (long)Math.Sqrt(z2);
if (z * z == z2 && x + y + z <= n)
res.Add(x + "," + y + "," + z);
}
});
When ran individually on a i5-8400 CPU, I get these results:
N: 10; Solutions: 1;
Time elapsed: 0.03 ms (Not parallel, int)
N: 100; Solutions: 6;
Time elapsed: 0.05 ms (Not parallel, int)
N: 1000; Solutions: 55;
Time elapsed: 0.3 ms (Not parallel, int)
N: 10000; Solutions: 543;
Time elapsed: 13.1 ms (Not parallel, int)
N: 100000; Solutions: 5512;
Time elapsed: 849.4 ms (Parallel, long)
You must use long when N is greater than 36340, because when it's squared, it overflows an int's max value. Finally, the parallel version starts to get better than the simple one when N is around 23000, with ints.
No time to properly test it, but seemed to yield the same results as your code (at 100 -> 6 results and at 1000 -> 55 results).
With N=1000 a time of 2ms vs your 144ms also without List
and N=10000 a time of 28ms
var N = 1000;
var c = 0;
for (int x = 2; x < N; x+=2)
{
for (int y = x; y < (N - x); y+=2)
{
long z2 = x * x + y * y + 1;
int z = (int) Math.Sqrt(z2);
if (x + y + z > N)
break;
if (z * z == z2)
c++;
}
}
Console.WriteLine(c);
#include<iostream>
#include<math.h>
int main()
{
int N = 10000;
int c = 0;
for (int x = 2; x < N; x+=2)
{
for (int y = x; y < (N - x); y+=2)
{
auto z = sqrt(x * x + y * y + 1);
if(x+y+z>N){
break;
}
if (z - (int) z == 0)
{
c++;
}
}
}
std::cout<<c;
}
This is my solution. On testing the previous solutions for this problem I found that x,y are always even and z is odd. I dont know the mathematical nature behind this, I am currently trying to figure that out.
I want to get it done in C# and it should be covering all the test
cases based on condition provided in the question.
The basic code, converted to long to process the N <= 100000 upper limit, with every optimizaion thrown in I could. I used alternate forms from #Mat's (+1) Wolfram Alpha query to precompute as much as possible. I also did a minimal perfect square test to avoid millions of sqrt() calls at the upper limit:
public static void Main()
{
int c = 0;
long N = long.Parse(Console.ReadLine());
long N_squared = N * N;
double half_N_squared = N_squared / 2.0 - 0.5;
double x_limit = N - Math.Sqrt(2) / 2.0 * Math.Sqrt(N_squared + 1);
for (long x = 2; x < x_limit; x += 2)
{
long x_squared = x * x + 1;
double y_limit = (half_N_squared - N * x) / (N - x);
for (long y = x; y < y_limit; y += 2)
{
long z_squared = x_squared + y * y;
int digit = (int) z_squared % 10;
if (digit == 3 || digit == 7)
{
continue; // minimalist non-perfect square elimination
}
long z = (long) Math.Sqrt(z_squared);
if (z * z == z_squared)
{
c++;
}
}
}
Console.WriteLine(c);
}
I followed the trend and left out "the degenerate solution" as implied by the OP's code but not explicitly stated.

Is there a way to designate X in y = (k1 + k2 × x) mod (s)?

I'm writting program in c# that needs to find X where greatest common divisor of k2 and s is 1, x is smaller than s and k1,k2,y,s are constants. Right now, I'm doing it by tring every value of X and checking if they are right, but that is very time consumig when I have like 40000+ values in it. Or if it's easier for you, you can try to designate X from y=x mod(s).
There is code I'm using right now to solve it:
if (GCD(k2, k) == 1)
{
for (int i = 0; i < k; i++)
{
n1 = 0;
n = 0;
while(n < 1)
{
if(i == (k1 + k2 * n1) % k){
s1[n1] = s[i];
n++;
}
n1++;
}
}
}
Thanks in advance.
P.S. If something is unclear, then let me know, it's kind of hard for me to explain all this :P
Let's go through a sample problem:
Solve for X:
17395 = (100 + 43 * X ) % 633424
Start by eliminating the addition:
17395 - 100 = (43 * X) % 633424
17294 = (43 * X) % 633424
Now, suppose there exists a number Y such that
1 = ( Y * 43 ) % 633424
(Aside: How do we know that Y exists? It exists iff 43 and 633424 are coprime, which they are. This is a particular case of Bézout's identity.)
Y is the multiplicative inverse of 43 with respect to 633424.
How does this help? We can multiply both sides by 17294:
17294 = ( Y * 43 * 17294 ) % 633424
And now we can read off our solution: X is Y * 17294.
So the problem reduces to computing the multiplicative inverse. Can you see how to find a number Y such that 1 = ( Y * 43 ) % 633424 ? If you can find that number then you can find X.
You can use Euclid's Algorithm to quickly find the multiplicative inverse. See https://en.wikipedia.org/wiki/Modular_multiplicative_inverse or my page on the subject https://ericlippert.com/2013/11/12/math-from-scratch-part-thirteen-multiplicative-inverses/

ProjectEuler Q1 Program unexpected result

I was working on problem one and my original program looked like this
int multiplesof=1000,count=0, multiple1 = 3, multiple2 = 5,val1,val2,sum=0;
while (count < multiplesof)
{
if (count % multiple1 == 0)
sum = sum += count;
if (count % multiple2 == 0)
sum = sum += count;
count++;
}
Console.Out.WriteLine(sum + " is the sum of all multiples");
Console.In.ReadLine();
It give me the solution of 266333. This proved to be wrong, stumped I looked at Google. I have since gotten the correct value of 233168 with the following loop. However to me they look like they do exactly the same thing. Could anyone please explain why they are bring up different answers?
while (count < multiplesof)
{
if (count % multiple1 == 0 || count % multiple2 == 0)
sum = sum += count;
count++;
}
Because you added twice if it was a multiple of both 3 and 5, like when it was 15.
An alternative solution and also a spoiler if you were going to try to solve it yourself:
int result = 3 * (999 / 3 * (999 / 3 + 1) / 2) + 5 * (999 / 5 * (999 / 5 + 1) / 2) - 15 * (999 / 15 * (999 / 15 + 1) / 2);
Think about numbers that are divisible by both 3 and 5, such as 15. Your first attempt counts them twice.

% (mod) explanation

Today I was writing a program in C#, and I used % to calculate some index... My program didn't work, so I debugged it and I realized that "%" is not working like in other program languages that I know.
For example:
In Python % returns values like this:
for x in xrange (-5, 6):
print x, "% 5 =", x % 5
-5 % 5 = 0
-4 % 5 = 1
-3 % 5 = 2
-2 % 5 = 3
-1 % 5 = 4
0 % 5 = 0
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0
In C#:
for (int i = -5; i < 6; i++)
{
Console.WriteLine(i + " % 5 = " + i % 5);
}
-5 % 5 = 0
-4 % 5 = -4
-3 % 5 = -3
-2 % 5 = -2
-1 % 5 = -1
0 % 5 = 0
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0
Did I do something wrong or is % not working like it should?
As explained in the comments, the different behaviour is by design. The different languages just ascribe different meanings to the % operator.
You ask:
How can I use modulus operator in C#?
You can define a modulus operator yourself that behaves the same way as the Python % operator:
int mod(int a, int n)
{
int result = a % n;
if ((result<0 && n>0) || (result>0 && n<0)) {
result += n;
}
return result;
}
Both answers are correct. Although personally I think the "always positive" one makes more sense.
You can define your own modulus function that only gives positive answers like this:
int mod(int a, int n) {
return ((a%n)+n) % n;
}
In modular arithmetic, one defines classes of numbers based on the modulo. In other words, in modulo m arithmetic, a number n is equivalent (read: the same) to n + m, n - m, n + 2m, n - 2m, etc.
One defines m "baskets" and every number falls in one (and only one) of them.
Example: one can say "It's 4:30 pm" or one can say "It's 16:30". Both forms mean exactly the same time, but are different representations of it.
Thus both, the Python and C# results are correct! The numbers are the same in the modulo 5 arithmetic you chose. It would also have been mathematically correct to return (5, 6, 7, 8, 9) for example. Just a bit odd.
As for the choice of representation (in other words, the choice on how to represent negative numbers), that is just a case of different design choices between the two languages.
However, that is not at all what the % operator actually does in C#. The % operator is not the canonical modulus operator; it is the remainder operator. The A % B operator actually answer the question "If I divided A by B using integer arithmetic, what would the remainder be?"
— What's the difference? Remainder vs Modulus by Eric Lippert
Quick snippet to get the canonical modulus:
return ((n % m) + m) % m;
Test implementation:
Mono/C#:
machine:~ user$ cat mod.cs
using System;
public class Program
{
public static void Main (string[] args)
{
Console.WriteLine(Mod(-2, 5));
Console.WriteLine(Mod(-5, 5));
Console.WriteLine(Mod(-2, -5));
}
public static int Mod (int n, int m)
{
return ((n % m) + m) % m;
}
}
machine:~ user$ mono mod.exe
3
0
-2
Python:
machine:~ user$ cat mod.py
print -2%5;
print -5%5;
print -2%-5;
machine:~ user$ python mod.py
3
0
-2

Categories

Resources