I'm trying to write a program for reversing numbers in binary. For instance, the binary representation of 13 is 1101, and reversing it gives 1011, which corresponds to number 11 right?
Here's my code:
static void Main(string[] args)
{
Console.WriteLine("Enter a Number");
int numb = int.Parse(Console.ReadLine());
int reverse = 0;
while (numb > 0)
{
int rem = numb % 10;
reverse = (reverse * 10) + rem;
numb = numb / 10;
}
Console.WriteLine("Reverse number={0}", reverse);
Console.ReadLine();
}
By this code I only get the numbers to reverse (13 -> 31)...
The input should contain a single line with an integer N, 1≤N≤1000000000 and I want my output in one line with one integer, the number I want to get by reversing the binary representation of N.
Something like that
// 13 = 1101b
int value = 13;
// 11 = 1011b
int result = Convert.ToInt32(new String(
Convert.ToString(value, 2)
.Reverse()
.ToArray()), 2);
Explanation:
Convert.ToString(value, 2) returns value in binary representation ("1101")
Reverse().ToArray() - reverse the string ('1','0','1','1') as sequence of characters and converts to array char[].
new String(...) constructs string "1011" from array of char
finally, Convert.ToInt32(..., 2) convert binary representation back to int
You can use Convert.ToString and Convert.ToInt32 methods, where 2 means binary:
int numb = int.Parse(Console.ReadLine());
var reversedString = Convert.ToString(numb, 2).ReverseString();
var result = Convert.ToInt32(reversedString, 2);
...
public static string ReverseString(this string s)
{
char[] arr = s.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
A fun excercise would be doing this without using the string conversion.
I have very little experience with bit twiddling so there is probably a faster and better way of doing this, but this seems to work:
public static IEnumerable<bool> ToBinary(this int n)
{
for (int i = 0; i < 32; i++)
{
yield return (n & (1 << i)) != 0;
}
}
public static int ToInt(this IEnumerable<bool> b)
{
var n = 0;
var counter = 0;
foreach (var i in b.Trim().Take(32))
{
n = n | (i ? 1 : 0) << counter;
counter++
}
return n;
}
private static IEnumerable<bool> Trim(this IEnumerable<bool> list)
{
bool trim = true;
foreach (var i in list)
{
if (i)
{
trim = false;
}
if (!trim)
{
yield return i;
}
}
}
And now you'd call it like this:
var reversed = n.ToBinary().Reverse().ToInt();
Related
I am currently working on an assignment where I need to write a small program that will take a generic string and should output how many possible anagrams that could be generated from the string.
The string that is the input can be up to 100 chars long and could include both lowercase and uppercase, in this case both lowercase and uppercase are considered distinct. The output should only be how many possible combinations, so I don't need to output the actual anagrams.The maximum timelimit is 1 second per string.
I have tried a number of diffrent ways of doing this, but one conclusion is that this should be solvable using some type of mathemathical algorithm.
The latest code I have tried with is this:
static void Main(string[] args)
{
string line;
while ((line = Console.ReadLine()) != null)
{
var uniqueStringArr = removeDuplicates(line);
Console.WriteLine(countDistinctPermutations(new string(uniqueStringArr)));
}
}
private static char[] removeDuplicates(string line)
{
var list = line.ToList();
return list.Distinct().ToArray();
}
static int MAX_CHAR = 100;
// Utility function to find factorial of n.
static int factorial(int n)
{
int fact = 1;
for (int i = 2; i <= n; i++)
fact = fact * i;
return fact;
}
// Returns count of distinct permutations
// of str.
static int countDistinctPermutations(String str)
{
int length = str.Length;
int[] freq = new int[MAX_CHAR];
// finding frequency of all the lower case
// alphabet and storing them in array of
// integer
for (int i = 0; i < length; i++)
if (str[i] >= 'a')
freq[str[i] - 'a']++;
// finding factorial of number of appearances
// and multiplying them since they are
// repeating alphabets
int fact = 1;
for (int i = 0; i < MAX_CHAR; i++)
fact = fact * factorial(freq[i]);
// finding factorial of size of string and
// dividing it by factorial found after
// multiplying
return factorial(length) / fact;
}
The thing is that this code does not give the correct answer for all my testcases.
The following sample data was provided for me :
Input string | Number of possible anagrams
at | 2
ordeals | 5040
abcdefghijklmnopqrstuvwxyz | 403291461126605635584000000
abcdefghijklmabcdefghijklm | 49229914688306352000000
abcdABCDabcd | 29937600
My code fixes the first two examples, but I get completly diffrent numbers for the other 3.
Is there anyone who can help me with this problem because I am running out of ideas ?
/Andreas
static BigInteger Factorial(long x)
{
return x <= 1 ? 1 : x * Factorial(x-1);
}
private static BigInteger NumberOfDistinctPermutationOf(string str)
{
BigInteger dividend = Factorial(str.Length);
foreach (char chr in str)
{
dividend /= Factorial(str.Count(c => c == chr));
str = str.Replace(chr.ToString(), string.Empty);
}
return dividend;
}
Description:
BigInteger Struct: Represents an arbitrarily large signed integer.
Enumerable.Count Method: Returns a number that represents how many elements in the specified sequence satisfy a condition.
String.Replace(String, String) Method: Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
GetNumberOfDistinctPermutation Method: Divides factorial of the length of the string by factorial of the number of occurrences of the char and then removes all occurrences of the char, for each char in the string.
static void Main(string[] args)
{
string line;
while ((line = Console.ReadLine()) != null)
{
Console.WriteLine($"{line} -> {countDistinctPermutations(line)}");
}
}
static BigInteger factorial(int n)
{
double fact = 1;
for (int i = 2; i <= n; i++)
fact = fact * i;
return fact;
}
static BigInteger countDistinctPermutations(String str)
{
// get a collection of {letter,occurences}
var duplicates = Array.GroupBy(p => p).Select(x => new { x.Key, count = x.Count() }).Where(x => x.count > 1);
BigInteger result = factorial(str.Length);
// foreach letter where occurence > 1 divide total permutations by the permutations for the occurence value (occurrence!)
foreach (var d in duplicates)
{
result /= factorial(d.count);
}
return result;
}
I only write code for a week so it's not that pretty but it works 100%.
static void Main(string[] args)
{
string inputData = Console.ReadLine();
Console.WriteLine(Solution(inputData));
}
static char[] convert(string text) // converting string to char[]
{
char[] newString = new char[text.Length];
for (int i = 0; i < text.Length; i++)
{
newString[i] = text[i];
}
return newString;
}
static double CalculateFctorial(double number) // calc. factorial
{
double factorial = 1;
for (int i = 1; i <= number; i++)
factorial *= i;
return factorial;
}
static int CountOcc(string text, char zet) // counting occurrences
{
int count = 0;
for (int i = 0; i < text.Length; i++)
{
if (text[i] == zet)
{
count++;
}
}
return count;
}
static double Solution(string text) // the soluton, counting occurences of
// each char in string and each factorial
{
double net = 0;
double sol = 1;
char[] newText = convert(text);
for (int i = 0; i <= newText.Length; i++)
{
if (text.Length > 0)
{
net = CountOcc(text, newText[i]);
sol = sol * CalculateFctorial(net);
if (newText[i] == text[0])
{ text = text.Trim(text[0]); }
}
}
double solution = CalculateFctorial(newText.Length) / sol;
return solution;
}
My question is that i have a list of binary string like below :
list=<"1111","1010","1010","0011">
and an input string of binary value st1=1010. I want to Xor between :
st3=st1 Xor list<0>
then :
st3=st3 Xor list<1>
st3=st3Xor list <2>;
st3=st3 Xor list <3>;
where the operation will be st1 Xor with first key in keys list and the result Xor with the second key in keys list and the result Xor with the third key in keys list and so on . Can any one help me please?
i have tried this code but it does not work as i expected :
foreach (string k in keys)
{
string st1 = textBox1.text;
string st2 = k;
string st3;
st3 = "";
//i wanted to make the length of both strings st1 and st2 equal
//here if the length of st1 greater than st2
if (st1.Length > st2.Length)
{
int n = st1.Length - st2.Length;
string pad = "";
for (int j = 1; j <= n; j++)
{ pad += 0; }
string recover = pad.ToString() + st2;
//this is my Xor operation that i made for string values
for (int counter = 0; counter < st1.Length; counter++)
{
if (st1[counter] != recover[counter])
{
st3 = st3 + '1';
}
else
{ st3 = st3 + '0'; }
}
listBox4.Items.Add("Xor :" + st3.ToString());
}
//here if st1 is less than st2
else if (st1.Length < st2.Length)
{
int nn = st2.Length - st1.Length;
string ppad = "";
for (int j = 1; j <= nn; j++)
{
ppad += 0;
}
string recover = ppad.ToString() + st1;
for (int counter = 0; counter < st2.Length; counter++)
{
if (st2[counter] != recover[counter])
{
st3 = st3 + '1';
}
else
{ st3 = st3 + '0'; }
}
listBox4.Items.Add("Xor :" + st3.ToString());}
//here if st1 equal st2
else
{
for (int counter = 0; counter < st1.Length; counter++)
{
if (st1[counter] != st2[counter])
{
st3 = st3 + '1';
}
else
{ st3 = st3 + '0'; }
}
listBox4.Items.Add("Xor :" + st3.ToString());
}
}
the result that i do not expected is :
Here's one approach (Arbitrary length binary strings):
Convert the strings back to integers BigIntegers, so that we can actually get the utility of existing bitwise Xor operator (^).
Use LINQ's Aggregate to consecutively left-fold the seed value (st1) with the converted list with Xor.
Since you seem interested only in the lowest 4 bits, I've applied a mask, although if all your numbers are strictly 4 bits, this isn't actually necessary (since 0 Xor 0 stays 0)
You can convert the int back to a binary string with Convert.ToString(x, 2) and then PadLeft to replace any missing leading zeroes.
Edit - OP has changed the question from an example 4 bit number and the requirement is now to work with arbitrary length binary strings. This approach still works, but we'll need to use BigInteger (which still has an XOR ^ operator), but we need helpers to parse and format binary strings, as these aren't built into BigInteger. The BitMask and padding have also been removed, since the strings aren't fixed length - the result will have at most 1 leading zero:
var list = new List<string>{"10101010101010101101","1101010101010101011",
"1110111111010101101","11111111111111111111111111","10101010110101010101"};
var listNum = list.Select(l => BinaryStringToBigInteger(l));
var st1 = "000000001";
var seedNumber = BinaryStringToBigInteger(st1);
var chainedXors = listNum.Aggregate(seedNumber, (prev, next) => prev ^ next);
// Back to binary representation of the string
var resultString = chainedXors.ToBinaryString();
And because there's no native support for converting BigIntegers to / from binary strings, you'll need a conversion helper such as Douglas's one here:
BigInteger BinaryStringToBigInteger(string binString)
{
return binString.Aggregate(BigInteger.Zero, (prev, next) => prev * 2 + next - '0');
}
And for the reverse operation, ToBinaryString is from this helper.
32 Bit Integer answer
If the Binary strings are 32 bits or less, then a much simpler solution exists, since there are out of the box conversions to / from binary strings. The same approach should apply for 64 bit longs.
var list = new List<string>{"1111","1010","1010","0011","0011"};
var listNum = list.Select(l => Convert.ToInt32(l, 2));
// If you only want the last 4 bits. Change this to include as many bits as needed.
var bitMask = Convert.ToInt32("00000000000000000000000000001111", 2);
var st1 = "1010";
var someNum = Convert.ToInt32(st1, 2);
var chainedXors = listNum.Aggregate(someNum, (prev, next) => prev ^ next);
// If you need the result back as a 4 bit binary-string, zero padded
var resultString = Convert.ToString(chainedXors & bitMask, 2)
.PadLeft(4, '0');
Try this code:
static void Main(string[] args)
{
List<string> list = new List<string> { "1111", "1010", "1010", "0011" };
string st1 = "1010";
foreach (string item in list)
{
st1 = XorBins(st1, item);
Console.WriteLine(st1);
}
Console.ReadKey();
}
private static string XorBins(string bin1, string bin2)
{
int len = Math.Max(bin1.Length, bin2.Length);
string res = "";
bin1 = bin1.PadLeft(len, '0');
bin2 = bin2.PadLeft(len, '0');
for (int i = 0; i < len; i++)
res += bin1[i] == bin2[i] ? '0' : '1';
return res;
}
Here is an Xor method for you:
public static string Xor(string s1, string s2) {
// find the length of the longest of the two strings
int longest = Math.Max(s1.Length, s2.Length);
// pad both strings to that length. You don't need to write the padding
// logic yourself! There is already a method that does that!
string first = s1.PadLeft(longest, '0');
string second = s2.PadLeft(longest, '0');
// Enumerable.Zip takes two sequences (in this case sequences of char, aka strings)
// and lets you transform each element in the sequences. Here what
// I did was check if the two chars are not equal, in which case
// I transform the two elements to a 1, 0 otherwise
return string.Join("", Enumerable.Zip(first, second, (x, y) => x != y ? '1' : '0'));
}
You can use it like this:
Xor("1111", "1010") // 0101
For instance, if the input is set to 1234, the program will return 11213141 because digit 1 occurs once, digit 2 occurs once ... so on and so forth.
Another example: 142225 => 11234151
My program works fine with small input but if the input has 10 digits or more, the result would make no sense. Please help.
class Example
{
// Get sorted(ascending) list for each digit in num
public static List<int> GetList(long num)
{
List<int> listOfInts = new List<int>();
while (num > 0)
{
int remainder = (int) num % 10;
listOfInts.Add(remainder);
num = num / 10;
}
listOfInts.Sort();
return listOfInts;
}
// Get minimum digit in the list
public static int getMinimumInt(List<int> l)
{
int min = 10;
foreach (int s in l)
{
if (s <= min)
{
min = s;
}
}
return min;
}
// Get count of the minimum digit specified
public static int getCount(int i,List<int> l)
{
int count = 0;
foreach (int s in l)
{
if (s == i)
{
count++;
}
}
return count;
}
public static void Main()
{
long input = 1234567891020; // Arbituary input
// initialize
List<int> outputList=new List<int>(); // List that would be eventually outputted
List<int> listOfInt = new List<int>();
listOfInt = GetList(input);
//Loop end till no element left in listOfInt
while ((listOfInt.ToArray()).Length!=0)
{
int item = getMinimumInt(listOfInt);
int count = getCount(item, listOfInt);
outputList.Add(item); // Add the item to be counted
outputList.Add(count); // Add count of the item
listOfInt.RemoveRange(0, count); // Remove digits that have been counted
}
// Output the list
foreach (int i in outputList)
{
Console.Write(i);
}
Console.WriteLine();
Console.ReadLine();
}
}
}
In your GetList() function, you are casting your 10+ digit long to an integer:
int remainder = (int) num % 10;
Attempting to place a 10+ digit number into an int means you are running up against the highest value of 32-bit integers, which is 2,147,483,647. That would explain why your results seem strange.
Use a long instead. If that isn't enough you can try System.Numerics.BigInteger, which will allow you to add more digits to it until you run out of memory.
You can use this LINQ approach, it doesn't care about numbers, just chars:
string output = String.Concat(input
.GroupBy(c => c)
.Select(g => String.Format("{0}{1}", g.Key, g.Count())));
If you want the result as long use long.TryParse(output, out longvariable).
int sourceVal = 12341231;
string sourceStr = sourceVal.ToString();
List<char> uniqueChars = null;
#if LINQ
uniqueChars = sourceStr.ToCharArray().Distinct().ToList();
#else
uniqueChars = new List<char>();
foreach (char c in sourceStr)
if (!uniqueChars.Contains(c))
uniqueChars.Add(c);
#endif
string result = "";
foreach (var wantedChar in uniqueChars)
#if LINQ
result += wantedChar.ToString() + (sourceStr.Count(f => f == wantedChar)).ToString();
#else
result += wantedChar.ToString() + (sourceStr.Split(wantedChar).Length - 1).ToString();
#endif
Console.WriteLine("Result = " + result);
This was my code to keep it as similar to yours. If you want to limit the count, use a modulus on the end (% 10) to keep the count to a single digit.
Having now seen the other Linq answer, I think that is a lot neater. Given that your maximum answer would be something like 192,939,495,969,798,999 if sorted in character order ascending, you would need a long not an int to store that.
Just change
int remainder = (int) num % 10;
to
int remainder = (int)(num % 10);
The first one is casting num to int then doing the mod 10. This will result in overflow when num is larger than int.MaxValue, typically a negative number. The second does the mod 10 first then the cast, which is safe as the mod will result in a value that can easily fit into an int.
I need to convert int to bin and with extra bits.
string aaa = Convert.ToString(3, 2);
it returns 11, but I need 0011, or 00000011.
How is it done?
11 is binary representation of 3. The binary representation of this value is 2 bits.
3 = 20 * 1 + 21 * 1
You can use String.PadLeft(Int, Char) method to add these zeros.
// convert number 3 to binary string.
// And pad '0' to the left until string will be not less then 4 characters
Convert.ToString(3, 2).PadLeft(4, '0') // 0011
Convert.ToString(3, 2).PadLeft(8, '0') // 00000011
I've created a method to dynamically write leading zeroes
public static string ToBinary(int myValue)
{
string binVal = Convert.ToString(myValue, 2);
int bits = 0;
int bitblock = 4;
for (int i = 0; i < binVal.Length; i = i + bitblock)
{ bits += bitblock; }
return binVal.PadLeft(bits, '0');
}
At first we convert my value to binary.
Initializing the bits to set the length for binary output.
One Bitblock has 4 Digits. In for-loop we check the length of our converted binary value und adds the "bits" for the length for binary output.
Examples:
Input: 1 -> 0001;
Input: 127 -> 01111111
etc....
You can use these methods:
public static class BinaryExt
{
public static string ToBinary(this int number, int bitsLength = 32)
{
return NumberToBinary(number, bitsLength);
}
public static string NumberToBinary(int number, int bitsLength = 32)
{
string result = Convert.ToString(number, 2).PadLeft(bitsLength, '0');
return result;
}
public static int FromBinaryToInt(this string binary)
{
return BinaryToInt(binary);
}
public static int BinaryToInt(string binary)
{
return Convert.ToInt32(binary, 2);
}
}
Sample:
int number = 3;
string byte3 = number.ToBinary(8); // output: 00000011
string bits32 = BinaryExt.NumberToBinary(3); // output: 00000000000000000000000000000011
public static String HexToBinString(this String value)
{
String binaryString = Convert.ToString(Convert.ToInt32(value, 16), 2);
Int32 zeroCount = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(binaryString.Length) / 8)) * 8;
return binaryString.PadLeft(zeroCount, '0');
}
Just what Soner answered use:
Convert.ToString(3, 2).PadLeft(4, '0')
Just want to add just for you to know. The int parameter is the total number of characters that your string and the char parameter is the character that will be added to fill the lacking space in your string. In your example, you want the output 0011 which which is 4 characters and needs 0's thus you use 4 as int param and '0' in char.
string aaa = Convert.ToString(3, 2).PadLeft(10, '0');
This may not be the most elegant solution but it is the fastest from my testing:
string IntToBinary(int value, int totalDigits) {
char[] output = new char[totalDigits];
int diff = sizeof(int) * 8 - totalDigits;
for (int n = 0; n != totalDigits; ++n) {
output[n] = (char)('0' + (char)((((uint)value << (n + diff))) >> (sizeof(int) * 8 - 1)));
}
return new string(output);
}
string LongToBinary(int value, int totalDigits) {
char[] output = new char[totalDigits];
int diff = sizeof(long) * 8 - totalDigits;
for (int n = 0; n != totalDigits; ++n) {
output[n] = (char)('0' + (char)((((ulong)value << (n + diff))) >> (sizeof(long) * 8 - 1)));
}
return new string(output);
}
This version completely avoids if statements and therfore branching which creates very fast and most importantly linear code. This beats the Convert.ToString() function from microsoft by up to 50%
Here is some benchmark code
long testConv(Func<int, int, string> fun, int value, int digits, long avg) {
long result = 0;
for (long n = 0; n < avg; n++) {
var sw = Stopwatch.StartNew();
fun(value, digits);
result += sw.ElapsedTicks;
}
Console.WriteLine((string)fun(value, digits));
return result / (avg / 100);//for bigger output values
}
string IntToBinary(int value, int totalDigits) {
char[] output = new char[totalDigits];
int diff = sizeof(int) * 8 - totalDigits;
for (int n = 0; n != totalDigits; ++n) {
output[n] = (char)('0' + (char)((((uint)value << (n + diff))) >> (sizeof(int) * 8 - 1)));
}
return new string(output);
}
string Microsoft(int value, int totalDigits) {
return Convert.ToString(value, toBase: 2).PadLeft(totalDigits, '0');
}
int v = 123, it = 10000000;
Console.WriteLine(testConv(Microsoft, v, 10, it));
Console.WriteLine(testConv(IntToBinary, v, 10, it));
Here are my results
0001111011
122
0001111011
75
Microsofts Method takes 1.22 ticks while mine only takes 0.75 ticks
With this you can get binary representation of string with corresponding leading zeros.
string binaryString = Convert.ToString(3, 2);;
int myOffset = 4;
string modified = binaryString.PadLeft(binaryString.Length % myOffset == 0 ? binaryString.Length : binaryString.Length + (myOffset - binaryString.Length % myOffset), '0'));
In your case modified string will be 0011, if you want you can change offset to 8, for instance, and you will get 00000011 and so on.
I've recently started learning C# (having learnt other languages) and I'm trying to create a function that generates the fibonacci sequence to the 'nth' term using a while loop and then returns the value of the 'nth' term.
My current code is this:
void fibonacci(int n)
{
int[] terms = { 0, 1 };
int i = 2;
while (i<=n)
{
terms.Concat( terms[i-1] + terms[i-2] );
i += 1;
}
return terms[n];
}
My understanding of C# is very poor as visual studio is telling me that I can't use 'Concat' with int[] - I'm trying to append the array with the new values. Any help would be great.
Arrays in C# are fixed length.
If you want to use a variable length collection, use a strongly typed List<T> instead, which has an Add method:
int fibonacci(int n)
{
var terms = new List<int>{ 0, 1 };
int i = 2;
while (i<=n)
{
terms.Add( terms[i-1] + terms[i-2] );
i += 1;
}
return terms[n];
}
You can't append to an array. In .Net, arrays have constant size and you can't resize them after creation.
Instead, you should use List<int> and its Add() method.
You can for example use list and change your code to:
int fibonacci(int n)
{
List<int> terms = new List<int> { 0, 1 };
int i = 2;
while (i<=n)
{
terms.Add(terms[i-1] + terms[i-2]);
i += 1;
}
return terms[n];
}
You can't add items to an array as it has fixed length. Use List<int> instead of array
I'm surprised nobody mentioned fixing the array size.
Well, maybe I'm missing something, but you could do:
int[] FibonacciArray(int n)
{
int[] F = new int[n+1];
F[0] = 0;
F[1] = 1;
for (int i = 2; i <= n; ++i)
{
F[i] = F[i - 1] + F[i - 2];
}
return F;
}
It's in average 2.5x faster than the version using a list.
But as often there is no free-lunch: the drawback is that your memory consumption is not smoothed: you pay upfront for all the memory you'll need.
Don't append values to an array. arrays have static size and you can't resize them after creation.
use
List<int> and its Add() method instead of array.
here is your solution for fibonacci series.
int fibonacci(int n)
{
var terms = new List<int>{ 0, 1 };
int i = 2;
while (i<=n)
{
terms.Add( terms[i-1] + terms[i-2] );
i += 1;
}
return terms[n];
}
also can be done like this :
class FibonacciSeries
{
static void Main(string[] args)
{
Console.WriteLine("Enter a num till which you want fibonacci series : ");
int val = Convert.ToInt32(Console.ReadLine());
int num1, num2;
num1 = num2 = 1;
Console.WriteLine(num1);
if (val > num2)
{
while (num2 < val)
{
Console.WriteLine(num2);
num2 += num1;
num1 = num2 - num1;
}
}
Console.ReadLine();
}
}
in your array format here is the solution
public int[] FibonacciSeriesArray(int num)
{
int[] arr = new int[num+1];
arr[0] = 0;
arr[1] = 1;
for (int startnum = 2; startnum <= num; startnum++)
{
arr[startnum] = arr[startnum - 1] + arr[startnum - 2];
}
return arr;
}
I would do it as a recursion, and not as a loop.
private static int fibonacci(int fib)
{
if (fib == 2 || fib == 1)
{
return 1;
}
else
{
return fibonacci(fib - 1) + fibonacci(fib - 2);
}
}
Here's a much more efficient way of finding fibonnaci numbers.
public static IEnumerable<double> FibList(int n)
{
for (int i = 1; i <= n; i++)
{
yield return Math.Round(Fib(i));
}
}
public static double Fib(double n)
{
double golden = 1.61803398875;
return (n == 0 || n == 1) ? 1 : (Math.Pow(golden, n) - Math.Pow(-golden, -n))/Math.Sqrt(5);
}