Created
September 22, 2012 09:04
-
-
Save KvanTTT/3765609 to your computer and use it in GitHub Desktop.
Rational numbers counting (with inverse)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static long RationalNumber(long i, long j) | |
{ | |
if (j == 1) | |
{ | |
if (i == 0) | |
return 1; | |
else if (i == 1) | |
return 2; | |
} | |
long kronDelta = i == 0 ? 0 : 1; | |
long jSign = Math.Sign(j); | |
long result = ((i + j - 1) * (i + j - 2) + 2 * j + 2 * kronDelta) * (1 + jSign) / 2 | |
+ ((i - j - 1) * (i - j - 2) - 2 * j + 2 * kronDelta - 1) * (1 - jSign) / 2 | |
+ 1 - kronDelta; | |
return result; | |
} | |
public static void RationaNumberFromNumber(long n, out long i, out long j) | |
{ | |
if (n == 1) | |
{ | |
i = 0; j = 1; | |
return; | |
} | |
if (n == 2) | |
{ | |
i = 1; j = 1; | |
return; | |
} | |
double sqrt4n11 = Math.Sqrt(4 * n - 11); | |
ulong M = (ulong)((sqrt4n11 + 1) / 2); | |
i = (long)((M * M + M) / 2 - (ulong)((n - 3) / 2)); | |
long sign = n % 2 == 0 ? 1 : -1; | |
j = sign * Math.Abs((long)((sqrt4n11 + 3) / 2) - i); | |
} | |
static void Main(string[] args) | |
{ | |
for (long n = 1; n < 5000; n++) | |
{ | |
long i, j; | |
RationaNumberFromNumber(n, out i, out j); | |
Console.WriteLine("N(i,j) = {0}; i = {1}; j = {2}; N = {3}", n, i, j, RationalNumber(i, j)); | |
} | |
Console.ReadLine(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment