C# ModInverse Function - c#

Is there a built in function that would allow me to calculate the modular inverse of a(mod n)?
e.g. 19^-1 = 11 (mod 30), in this case the 19^-1 == -11==19;

Since .Net 4.0+ implements BigInteger with a special modular arithmetics function ModPow (which produces “X power Y modulo Z”), you don't need a third-party library to emulate ModInverse. If n is a prime, all you need to do is to compute:
a_inverse = BigInteger.ModPow(a, n - 2, n)
For more details, look in Wikipedia: Modular multiplicative inverse, section Using Euler's theorem, the special case “when m is a prime”. By the way, there is a more recent SO topic on this: 1/BigInteger in c#, with the same approach suggested by CodesInChaos.

int modInverse(int a, int n)
{
int i = n, v = 0, d = 1;
while (a>0) {
int t = i/a, x = a;
a = i % x;
i = x;
x = d;
d = v - t*x;
v = x;
}
v %= n;
if (v<0) v = (v+n)%n;
return v;
}

The BouncyCastle Crypto library has a BigInteger implementation that has most of the modular arithmetic functions. It's in the Org.BouncyCastle.Math namespace.

Here is a slightly more polished version of Samuel Allan's algorithm. The TryModInverse method returns a bool value, that indicates whether a modular multiplicative inverse exists for this number and modulo.
public static bool TryModInverse(int number, int modulo, out int result)
{
if (number < 1) throw new ArgumentOutOfRangeException(nameof(number));
if (modulo < 2) throw new ArgumentOutOfRangeException(nameof(modulo));
int n = number;
int m = modulo, v = 0, d = 1;
while (n > 0)
{
int t = m / n, x = n;
n = m % x;
m = x;
x = d;
d = checked(v - t * x); // Just in case
v = x;
}
result = v % modulo;
if (result < 0) result += modulo;
if ((long)number * result % modulo == 1L) return true;
result = default;
return false;
}

There is no library for getting inverse mod, but the following code can be used to get it.
// Given a and b->ax+by=d
long[] u = { a, 1, 0 };
long[] v = { b, 0, 1 };
long[] w = { 0, 0, 0 };
long temp = 0;
while (v[0] > 0)
{
double t = (u[0] / v[0]);
for (int i = 0; i < 3; i++)
{
w[i] = u[i] - ((int)(Math.Floor(t)) * v[i]);
u[i] = v[i];
v[i] = w[i];
}
}
// u[0] is gcd while u[1] gives x and u[2] gives y.
// if u[1] gives the inverse mod value and if it is negative then the following gives the first positive value
if (u[1] < 0)
{
while (u[1] < 0)
{
temp = u[1] + b;
u[1] = temp;
}
}

Related

Solving modulo in c#

I'm having troubles solving modulo in c#. The example below
7^-1 modulo 26
when on Wolfram Alpha returns correct 15. In c# when I tried direct:
1/7 % 26
it returns unwanted 0.142857142857143 instead of desired 15.
But i'm not a master mathematician, so i'm probably missing something vital.
Your are looking for modular inversion: in case of
7**-1 modulo 26 = x
or
1 / 7 modulo 26 = x
you actually want to find out an x such that
(x * 7) modulo 26 = 1
In our case x == 15 since
15 * 7 == 105 == 26 * 4 + 1
For small modulo values (like 26) you can find the answer (15) with a help of naive for loop:
int modulo = 26;
int div = 7;
int result = 0;
for (int i = 1; i < modulo; ++i)
if ((i * div) % modulo == 1) {
result = i;
break;
}
Console.Write(result);
In general case, you can obtain the result with a help of Extended Euclid Algorithm. Often, when working with modulo arithmetics we face huge numbers, that's why let me show the code for BigInteger; if it's not your case you can turn BigInteger to good old int.
Code:
using System.Numerics;
...
private static (BigInteger LeftFactor,
BigInteger RightFactor,
BigInteger Gcd) Egcd(this BigInteger left, BigInteger right) {
BigInteger leftFactor = 0;
BigInteger rightFactor = 1;
BigInteger u = 1;
BigInteger v = 0;
BigInteger gcd = 0;
while (left != 0) {
BigInteger q = right / left;
BigInteger r = right % left;
BigInteger m = leftFactor - u * q;
BigInteger n = rightFactor - v * q;
right = left;
left = r;
leftFactor = u;
rightFactor = v;
u = m;
v = n;
gcd = right;
}
return (LeftFactor: leftFactor,
RightFactor: rightFactor,
Gcd: gcd);
}
The inversion itself will be
private static BigInteger ModInversion(BigInteger value, BigInteger modulo) {
var egcd = Egcd(value, modulo);
if (egcd.Gcd != 1)
throw new ArgumentException("Invalid modulo", nameof(modulo));
BigInteger result = egcd.LeftFactor;
if (result < 0)
result += modulo;
return result % modulo;
}
Demo:
using System.Numerics;
...
BigInteger result = ModInversion(7, 26);
Console.Write(result);
Outcome:
15

Codewar task. How to find simple square numbers by the condition?

I tried to solve this problem on Codewar, but I don`t understand how to find exceptions.
In this Kata, you will be given a number n (n > 0) and your task will be to return the smallest square number N (N > 0) such that n + N is also a perfect square. If there is no answer, return -1 (nil in Clojure, Nothing in Haskell).
Here code that I wrote:
using System;
public class SqNum
{
public static long solve(long n){
int N = 1;
long lTemp = n;
double sum, result;
bool isSqare;
while(true)
{
sum = lTemp + N;
result = Math.Sqrt(sum);
isSqare = result % 1 == 0;
if(n == 4)
{
return -1;
}
if(isSqare == true)
{
return Convert.ToInt32(result);
}
N++;
}
return -1;
}
}
If N (square) is p^2, and n+N=r^2, you can write
n + p^2 = r^2
n = r^2 - p^2
n = (r - p) * (r + p)
If we represent n as product of pair of divisors:
n = a * b // let a<=b
a * b = (r - p) * (r + p)
We have system
r - p = a
r + p = b
and
p = (b - a) / 2
When p is the smallest? In the case of maximal close factors b and a. So we can try to calculate divisors starting from square root of n. Also note that a and b should have the same parity (to make p integer)
Pseudocode:
int N = -1;
for (int a = Math.Ceiling(Math.Sqrt(n)) - 1; a > 0; a--) {
if (n % a == 0) {
int bma = n / a - a;
if (bma % 2 == 0) {
int p = bma / 2;
int N = p * p;
break;
}
}
}
Examples:
n = 16
first divisor below sqrt(16) a = 2, b=8
p = 3, 16 + 9 = 25
n = 13
first divisor below sqrt(13) a = 1, b=13
p = 6, 13 + 36 = 49
n = 72
first divisor below sqrt(72) is a = 8, b= 9 - but distinct parity!
so the next suitable pair is a = 6, b = 12
p = 3, 72 + 9 = 81

Data histogram - optimized binwidth optimization

I'm looking to produce a data histogram from a given dataset. I've read about different options for constructing the histogram and I'm most interested in a method based on the work of
Shimazaki, H.; Shinomoto, S. (2007). "A method for selecting the bin
size of a time histogram"
The above method uses estimation to determine the optimal bin width and distribution, which is needed in my case because the sample data will vary in distribution and hard to determine the bin count and width in advance.
Can someone recommend a good source or a starting point for writing such a function in c# or have a close enough c# histogram code.
Many thanks.
The following is a port I wrote of the Python version of this algorithm from here. I know the API could do with some work, but this should be enough to get you started. The results of this code are identical to those produced by the Python code for the same input data.
public class HistSample
{
public static void CalculateOptimalBinWidth(double[] x)
{
double xMax = x.Max(), xMin = x.Min();
int minBins = 4, maxBins = 50;
double[] N = Enumerable.Range(minBins, maxBins - minBins)
.Select(v => (double)v).ToArray();
double[] D = N.Select(v => (xMax - xMin) / v).ToArray();
double[] C = new double[D.Length];
for (int i = 0; i < N.Length; i++)
{
double[] binIntervals = LinearSpace(xMin, xMax, (int)N[i] + 1);
double[] ki = Histogram(x, binIntervals);
ki = ki.Skip(1).Take(ki.Length - 2).ToArray();
double mean = ki.Average();
double variance = ki.Select(v => Math.Pow(v - mean, 2)).Sum() / N[i];
C[i] = (2 * mean - variance) / (Math.Pow(D[i], 2));
}
double minC = C.Min();
int index = C.Select((c, ix) => new { Value = c, Index = ix })
.Where(c => c.Value == minC).First().Index;
double optimalBinWidth = D[index];
}
public static double[] Histogram(double[] data, double[] binEdges)
{
double[] counts = new double[binEdges.Length - 1];
for (int i = 0; i < binEdges.Length - 1; i++)
{
double lower = binEdges[i], upper = binEdges[i + 1];
for (int j = 0; j < data.Length; j++)
{
if (data[j] >= lower && data[j] <= upper)
{
counts[i]++;
}
}
}
return counts;
}
public static double[] LinearSpace(double a, double b, int count)
{
double[] output = new double[count];
for (int i = 0; i < count; i++)
{
output[i] = a + ((i * (b - a)) / (count - 1));
}
return output;
}
}
Run it like this:
double[] x =
{
4.37, 3.87, 4.00, 4.03, 3.50, 4.08, 2.25, 4.70, 1.73,
4.93, 1.73, 4.62, 3.43, 4.25, 1.68, 3.92, 3.68, 3.10,
4.03, 1.77, 4.08, 1.75, 3.20, 1.85, 4.62, 1.97, 4.50,
3.92, 4.35, 2.33, 3.83, 1.88, 4.60, 1.80, 4.73, 1.77,
4.57, 1.85, 3.52, 4.00, 3.70, 3.72, 4.25, 3.58, 3.80,
3.77, 3.75, 2.50, 4.50, 4.10, 3.70, 3.80, 3.43, 4.00,
2.27, 4.40, 4.05, 4.25, 3.33, 2.00, 4.33, 2.93, 4.58,
1.90, 3.58, 3.73, 3.73, 1.82, 4.63, 3.50, 4.00, 3.67,
1.67, 4.60, 1.67, 4.00, 1.80, 4.42, 1.90, 4.63, 2.93,
3.50, 1.97, 4.28, 1.83, 4.13, 1.83, 4.65, 4.20, 3.93,
4.33, 1.83, 4.53, 2.03, 4.18, 4.43, 4.07, 4.13, 3.95,
4.10, 2.27, 4.58, 1.90, 4.50, 1.95, 4.83, 4.12
};
HistSample.CalculateOptimalBinWidth(x);
Check the Histogram function. If any data elements are unlucky to be equal to a bin boundary (other than the first or last bin), they will be counted in both consecutive bins.
The code needs to check (lower <= data[j] && data[j] < upper) and handle the case that all elements equal to xMax go into the last bin.
A small update to nick_w answer.
If you actually need the bins after. Plus optimized the double loop in histogram function away, plus got rid of linspace function.
/// <summary>
/// Calculate the optimal bins for the given data
/// </summary>
/// <param name="x">The data you have</param>
/// <param name="xMin">The minimum element</param>
/// <param name="optimalBinWidth">The width between each bin</param>
/// <returns>The bins</returns>
public static int[] CalculateOptimalBinWidth(List<double> x, out double xMin, out double optimalBinWidth)
{
var xMax = x.Max();
xMin = x.Min();
optimalBinWidth = 0;
const int MIN_BINS = 1;
const int MAX_BINS = 20;
int[] minKi = null;
var minOffset = double.MaxValue;
foreach (var n in Enumerable.Range(MIN_BINS, MAX_BINS - MIN_BINS).Select(v => v*5))
{
var d = (xMax - xMin)/n;
var ki = Histogram(x, n, xMin, d);
var ki2 = ki.Skip(1).Take(ki.Length - 2).ToArray();
var mean = ki2.Average();
var variance = ki2.Select(v => Math.Pow(v - mean, 2)).Sum()/n;
var offset = (2*mean - variance)/Math.Pow(d, 2);
if (offset < minOffset)
{
minKi = ki;
minOffset = offset;
optimalBinWidth = d;
}
}
return minKi;
}
private static int[] Histogram(List<double> data, int count, double xMin, double d)
{
var histogram = new int[count];
foreach (var t in data)
{
var bucket = (int) Math.Truncate((t - xMin)/d);
if (count == bucket) //fix xMax
bucket --;
histogram[bucket]++;
}
return histogram;
}
I would recommend binary search to speed up the assignment to the class intervals.
public void Add(double element)
{
if (element < Bins.First().LeftBound || element > Bins.Last().RightBound)
return;
var min = 0;
var max = Bins.Length - 1;
var index = 0;
while (min <= max)
{
index = min + ((max - min) / 2);
if (element >= Bins[index].LeftBound && element < Bins[index].RightBound)
break;
if (element < Bins[index].LeftBound)
max = index - 1;
else
min = index + 1;
}
Bins[index].Count++;
}
"Bins" is a list of items of type "HistogramItem" which defines properties like "Leftbound", "RightBound" and "Count".

Problem with return in C#

Because of asking my last question, I've changed my code to use return. I always have this problem with return: I know I should use return (where I comment in code below) but I dont know how should I define it to work? Thanks for your help.
public double bigzarb(int u, int v)
{
double n;
int x=0;
int y;
int w=0;
int z;
string[] i = textBox7.Text.Split(',');
int[] nums = new int[i.Length];
for (int counter = 0; counter < i.Length; counter++)
{
nums[counter] = Convert.ToInt32(i[counter]);
}
u = nums[0];
double firstdigits =Math.Floor(Math.Log10(u) + 1);
v = nums[1];
double seconddigits = Math.Floor(Math.Log10(v) + 1);
if (firstdigits >= seconddigits)
{
n = firstdigits;
}
else
{
n = seconddigits;
}
if (u == 0 || v == 0)
{
MessageBox.Show("the Multiply is 0");
}
string threshold = textBox9.Text;
int intthreshold = Convert.ToInt32(threshold);
int intn = Convert.ToInt32(n);
if (intn <= intthreshold)
{
double uv = u * v;
string struv = uv.ToString();
MessageBox.Show(struv);
///i know here should be a return but i dont know how to define it to work
}
else
{
int m = Convert.ToInt32(Math.Floor(n / 2));
x = u % 10 ^ m;
y = u / 10 ^ m;
w = v % 10 ^ m;
z = v / 10 ^ m;
return bigzarb(x, w) *Math.Pow(10,m) +(bigzarb(x,w)+bigzarb(w,y))*Math.Pow(10,m) +bigzarb(y,z);
}
}
arash, your problem isn't with that return, your problem is bigzarb() is declared as void which means it has no returning value yet you use it in your last line as bigzarb(x,w) * .... which will give you an error. Also, since you declared your bigzarb() as void, you cant return a value in it. Also ^ doesn't mean power of in .net, you should use Math.Power instead.
Edit: You should change your method from void bigzarb() to double bigzarb() and replace ^ with Math.Power and retry to see if yit works.
Last edit: Change your method return type to double from int and change the last line to:
return bigzarb(x, w) * Math.Pow(Convert.ToDouble(10), Convert.ToDouble(m)) + (bigzarb(x, w) + bigzarb(w, y)) * Math.Pow(Convert.ToDouble(10), Convert.ToDouble(m)) + bigzarb(y, z);
If your method is defined to "return void", you can't return some value.
So change that "void" into "int" or "double", whatever type of value you want to return.
The next question is what value do you want to return in that spot? Return that.
By the way: if you really don't want to return a value (ever!) then that "void" is correct and you should only use "return" without value (or let the method run until the last line of the method).
my tip to you is to structure your code, extract some of the code to separate functions with meaningful names and also rename your variables to sometging meaningful. That would make it easier to read, understand and you get a better "flow" in your code. Also, you should complement your text with an actual question. Try to insert an extra return statement in the if code block, it is perfectly fine to have multiple return statements.
if(logic check)
{
return something;
}
else
{
return something else;
}
You need to have return either in both statements or one return after the if-else block, otherwise you'll get somekind of compiler error saying that not all code paths returns a result or something similar.
You have only one return and it's a recursive call (calling itself) --> stack overflow! You need to have another return somewhere without a recursive call
public int bigzarb(int u, int v)
{
double n;
int x = 0;
int y;
int w = 0;
int z;
string[] i = textBox1.Text.Split(',');
int[] nums = new int[i.Length];
for (int counter = 0; counter < i.Length; counter++)
{
nums[counter] = Convert.ToInt32(i[counter]);
}
u = nums[0];
double firstdigits = Math.Floor(Math.Log10(u) + 1);
v = nums[1];
double seconddigits = Math.Floor(Math.Log10(v) + 1);
if (firstdigits >= seconddigits)
{
n = firstdigits;
}
else
{
n = seconddigits;
}
if (u == 0 || v == 0)
{
MessageBox.Show("the Multiply is 0");
}
//string threshold = textBox9.Text;
int intthreshold = Convert.ToInt32(textBox9.Text);//Edited by me
int intn = Convert.ToInt32(n);
if (intn <= intthreshold)
{
double uv = u * v;
string struv = uv.ToString();
MessageBox.Show(struv);
///i know i should use return here but how can i implement that to work?
}
else
{
int m = Convert.ToInt32(Math.Floor(n / 2));
x = u % 10 ^ m;
y = u / 10 ^ m;
w = v % 10 ^ m;
z = v / 10 ^ m;
return bigzarb(x, w) * (10 ^ m) + (bigzarb(x, w) + bigzarb(w, y)) * 10 ^ m + bigzarb(y, z);
}
return 0;
}
Its a confusing one.since your function contains Void as return type
Declare the integer variable for returning the values
Ex:
public int func()
{
int l_nData = 0;
if(condition)
{
l_nData = 1;
return l_nData;
}
else
{
l_nData = 2;
return l_nData;
}
return l_nData;
}

Quickest Method to Reverse in String in C#.net

I'm currently writing a quick solution for Euler Problem #4 where one must find the largest palindromic number from the product of two 3-digit numbers.
To identify if a number is palindromic, you would obviously compare a reverse of the number with the original.
Since C# doesn't have a built in String.Reverse() method, what is the quickest way to reverse a string?
I will be testing all the suggested solution in a loop with 100,000,000 iterations. The correct answer will be given to the person who submitted the fastest solution.
I will be testing the solution in a C#.Net 3.5 console application
Wouldn't reversing the number be faster?
// unchecked code, don't kill me if it doesn't even compile.
ulong Reverse(ulong number) {
ulong result = 0;
while (number > 0) {
ulong digit = number % 10;
result = result * 10 + digit;
number /= 10;
}
return result;
}
A you want to compare a number with its reverse it may be faster to reverse the number using division rather than converting it to a string. I still need to test the speed of it.
private static int Reverse(int num) {
int res = 0;
while (num > 0) {
int rm ;
num = Math.DivRem(num, 10, out rm);
res = res * 10 + rm;
}
return res;
}
EDIT:
DivRem was about 1% faster than division and module in my computer.
A speed optimization is exit if the last digit is 0:
private static int Reverse(int num) {
int res = 0;
int rm;
num = Math.DivRem(num, 10, out rm);
//Some magic value or return false, see below.
if (rm == 0) return -1 ;
res = res * 10 + rm;
while (num > 0) {
num = Math.DivRem(num, 10, out rm);
res = res * 10 + rm;
}
return res ;
}
Making the method return a bool was slightly slower than comparing to a bool in a loop in my computer, but I don't understand why. Please test in your computer.
Multiplication and bit-shifing should be faster than division but probably are not precise enough. EDIT: using long seems be precise enough.
private static int FastReverse(int num) {
int res = 0;
int q = (int)((214748365L * num) >> 31);
int rm = num - 10 * q;
num = q;
if (rm == 0) return -1;
res = res * 10 + rm;
while (num > 0) {
q = (int)((214748365L * num) >> 31);
rm = num - 10 * q;
num = q;
res = res * 10 + rm;
}
return res;
}
(214748365L * num) >> 31 is equal to i / 10 until 1,073,741,829 where 1 / 10 gives 107374182 and the multiplication + binary shifting gives 107374183.
I think it might be faster to do the comparison in-place. If you reverse the string, you've got to:
Instantiate a new string object (or StringBuffer object)
Copy the data (in reverse) from the first string to the new string
Do your comparison.
If you perform the comparison in place, you do only the last step. An even then, your comparison is only half the string (or half - 0.5, in the event of an odd number of characters). Something like the following should work:
static bool IsPalindromic(string s){
int len = s.Length;
int half = len-- >> 1;
for(int i = 0; i < half; i++)
if(s[i] != s[len - i])
return false;
return true;
}
EDIT:
Although this answers the OP's question, the solutions offered by ggf31416 and configurator solve the OP's real need about 30% faster, by my tests. configurator's solution is a tiny bit faster than ggf31416's, if you convert it to a static method and use ints instead of ulongs (but much slower, otherwise).
Incidentally, running through these examples to solve the problem the OP mentions (finding the largest palindromic product of any two three-digit numbers) with the simple (perhaps naïve) loop below:
for(int i = 100; i < 1000; i++)
for(int j = i; j < 1000; j++) // calculations where j < i would be redundant
...
yields the following results on my machine:
IsPalindromic(product.ToString()) took 0.3064174 seconds.
ggf31416Reverse(product) == product took 0.1933994 seconds.
configuratorReverse(product) == product took 0.1872061 seconds.
Each produces the correct result of 913 * 993 = 906609.
Performance: Fastest string reversing algorithms... (final results)
string test = "ABC";
string reversed = new String(test.ToCharArray().Reverse().ToArray());
public static String Reverse(string input) {
var length = input.Length;
var buffer = new char[length];
for ( var i= 0; i < input.Length; i++ ) {
buffer[i] = input[(length-i)-1];
}
return new String(buffer);
}
EDIT: Doh! Forgot to halve the length for perf :)
The fastest way I have found to reverse a string in C# is with the following code. It's faster reading in 32bits at a time instead of a char's length of 16bits.
In debug mode, it is faster until you get to about 93 characters. Anything longer than that Array.Reverse() is faster. Using a release build and running outside of the IDE, this method will blow Array.Reverse() out of the water at any string length.
char[] MyCharArray = MyString.ToCharArray();
UIntStringReverse(ref MyCharArray); //Code to reverse is below.
string ReversedString = new string(MyCharArray);
private static unsafe void UIntStringReverse(ref char[] arr)
{
uint Temp;
uint Temp2;
fixed (char* arrPtr = &arr[0])
{
uint* p, q;
p = (uint*)(arrPtr);
q = (uint*)(arrPtr + arr.LongLength - 2);
if (arr.LongLength == 2)
{
Temp = *p;
*p = ((Temp & 0xFFFF0000) >> 16) | ((Temp & 0x0000FFFF) << 16);
return;
}
while (p < q)
{
Temp = *p;
Temp2 = *q;
*p = ((Temp2 & 0xFFFF0000) >> 16) | ((Temp2 & 0x0000FFFF) << 16);
*q = ((Temp & 0xFFFF0000) >> 16) | ((Temp & 0x0000FFFF) << 16);
p++;
q--;
}
}
}
try this too:
http://weblogs.sqlteam.com/mladenp/archive/2006/03/19/9350.aspx
string Reverse(string s)
{
return new string(s.ToCharArray().Reverse().ToArray());
}
Using ggf31416's FastReverse function, here is the solution to Project Euler's Problem #4 which completes on my computer in 47ms.
using System;
using System.Diagnostics;
namespace Euler_Problem_4
{
class Program
{
static void Main(string[] args)
{
Stopwatch s = new Stopwatch();
s.Start();
int t = 0;
for (int i = 999; i > 99; i--)
{
for (int j = i; j > 99; j--)
{
if (i*j == FastReverse(i*j))
{
if (i * j > t)
{
t = i * j;
}
}
}
}
Console.WriteLine(t);
s.Stop();
Console.WriteLine("{0}mins {1}secs {2}ms", s.Elapsed.Minutes, s.Elapsed.Seconds, s.Elapsed.Milliseconds);
Console.ReadKey(true);
}
private static int FastReverse(int num)
{
int res = 0;
int q = (int)((214748365L * num) >> 31);
int rm = num - 10 * q;
num = q;
if (rm == 0) return -1;
res = res * 10 + rm;
while (num > 0)
{
q = (int)((214748365L * num) >> 31);
rm = num - 10 * q;
num = q;
res = res * 10 + rm;
}
return res;
}
}
}
The Stopwatch class needs reset after each run. the code below has been corrected
var d = s.ToCharArray();
Array.Reverse(d);
return s == new string(d);
using System;
using System.Diagnostics;
namespace longeststring_codegolf
{
class Program
{
static void Main(string[] args)
{
int t = 0, v = 0;
var sw = new Stopwatch();
sw.Start();
for (int i = 999; i > 99; i--)
for (int j = 999; j > 99; j--)
if ((v = i * j) > t && IsPalindromicMine(v.ToString()))
t = v;
sw.Stop();
var elapsed = sw.Elapsed;
var elapsedMilliseconds = sw.ElapsedMilliseconds;
var elapsedTicks = sw.ElapsedTicks;
Console.WriteLine("Ticks: " + elapsedTicks.ToString());//~189000
Console.WriteLine("Milliseconds: " + elapsedMilliseconds.ToString()); //~9
sw = Stopwatch.StartNew();
for (int i = 999; i > 99; i--)
for (int j = 999; j > 99; j--)
if ((v = i * j) > t && IsPalindromic(v.ToString()))
t = v;
sw.Stop();
var elapsed2 = sw.Elapsed;
var elapsedMilliseconds2 = sw.ElapsedMilliseconds;
var elapsedTicks2 = sw.ElapsedTicks;
Console.WriteLine("Ticks: " + elapsedTicks2.ToString());//~388000
Console.WriteLine("Milliseconds: " + elapsedMilliseconds2.ToString());//~20
}
static bool IsPalindromicMine(string s)
{
var d = s.ToCharArray();
Array.Reverse(d);
return s == new string(d);
}
static bool IsPalindromic(string s)
{
int len = s.Length;
int half = len-- >> 1;
for (int i = 0; i < half; i++)
if (s[i] != s[len - i])
return false;
return true;
}
}
}

Categories

Resources