Fibonacci numbers [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
So I have this problem where I have to calculate the Fibonacci number of any given number from the user. I don't know how to do the actual calculations part, but everything else works. Here's my code. Can someone help me with the calculation part?
using System;
namespace Assignment
{
class MainClass
{
public static void Main (string[] args)
{
int sum = 0;
Console.WriteLine("Fibonacci Number: ");
String fib = Console.ReadLine ();
double result = Convert.ToDouble (fib);
for(int i = 0; i <= result; i++)
{
sum = i * i - 1;
}
Console.WriteLine ("!" + result + " = " + sum);
}
}
}

Extension on recursion approach - use anonymous recursion (which uses Fibonacci as example of recursive call):
Define recursive function: f(n+1) = f(n) + f(n-1);.
Grab definition of Y-Combinator from the article:
delegate Func<A,R> Recursive<A,R>(Recursive<A,R> r);
static Func<A, R> Y<A, R>(Func<Func<A, R>, Func<A, R>> f)
{
Recursive<A, R> rec = r => a => f(r(r))(a);
return rec(rec);
}
Now use Y-combinator to construct recursive function:
Func<int,int> fib = Y<int,int>(f => n => n > 1 ? f(n - 1) + f(n - 2) : n);
Ready to call:
var fibOfSmallNumber = fib(4);
Now for large values you'd need BigInteger
Func<BigInteger,BigInteger> fibForBigNumbers =
Y<BigInteger,BigInteger>(f => n => n > 1 ? f(n - 1) + f(n - 2) : n);
var fibOfBigNumber = fib(4);
Don't expect it to return value in short amount of time - default recursive implementation is very slow. Instead you should apply Memoization to remember previous values of the function (which also covered in the article).

Do you know the definition of the Fibonacci numbers? Please look them up; they have nothing to do with the polynomial x² - 1. The point of the problem is for you to translate the algorithm into C♯.
There are three general approaches you'll find:
Iteration by a for loop.
Recursion.
Direct formulas using exponentiation.
Try it all three ways. I suggest you look at the textbook by Graham, Knuth, and Patashnik, Concrete Mathematics. You'll learn some of the history too.

If what you want is the nth fibonacci number something like this should work:
const double goldenratio = 1.6180339887;
int n = 16;
int nthfib = Math.Round(Math.Pow(goldenratio, n - 1) / Math.Sqrt(5));
nthfib will equal the 16th fibonacci number, 610.
Since the fibonacci sequence gets very large rather quickly, you might need a limit set on n so that nthfib doesn't max out.

Related

Fill in numbers in order between two numbers [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
Let's say you have two numbers, 4 and 9. The numbers can't be less than 0 or more than 9.
I want to fill the gap between 4 and 9 with numbers in correct order like so:
456789
How does one exactly do so? I've been stuck on this problem for the past 2 hours.
Thank you.
I have tried putting the numbers into an array and using the array's length as a way to fill in the numbers.
I've tried numerous other things that I don't know how to explain.
Just create a loop and loop thru all the integers between your numbers and add each number to a string if that is your desired output:
string CreateNumberSequence(int start, int end){
var sb = new StringBuilder();
for(int i = start; i <= end; i++){
sb.Add(i.ToString());
}
return sb.ToString();
}
Note that 10-12 would produce 101112, so you might want to add some separator between numbers, or just create a list of numbers and do the formatting separatly. You could also use Enumerable.Range, but if you are new to programming it is useful to know how to use plain loops.
If you want a list of numbers, change StringBuilder to List<int>, remove all the .ToString() and change the return-type. Or just use the previously mentioned Enumerable.Range.
You can use Enumerable.Range
int start = 4, end = 10;
int[] range = Enumerable.Range(start, end - start + 1).ToArray();
// range: 4 5 6 7 8 9 10
You can use the range method. since you know the start and end of the sequence you can put the start as 4 and the difference to the end from counting all the way from start will be 6.
and for 10-12 it will be like
var number = Enumerable.Range(10, 3);
var number = Enumerable.Range(4, 6);
var result = string.Join("", number.Select(x => x.ToString()).ToArray());
With extension methods :
public static class Ext
{
public static bool ToIntValue(this IEnumerable<int> source, out int output)
{
string joinedSource = string.Join(string.Empty, source);
return int.TryParse(joinedSource, out output);
}
public static IEnumerable<int> NumbersBetween(this int start, int end)
{
if (start > 0 && end <= 9 && start <= end)
{
for (int i = start; i <= end; i++)
yield return i;
}
else
{
throw new ArgumentException("Start and end must be beetween 1 and 9 and end must be bigger than start.");
}
}
}
use case :
if (1.NumbersBetween(9).ToIntValue(out int result))
{
Console.WriteLine(result);
}

Smth about Binet formula

Why does the Binet formula( O(LogN), but it is not exactly ) work worse in time than the iteration method( O(n) )?
static double SQRT5 = Math.Sqrt(5);
static double PHI = (SQRT5 + 1) / 2;
public static int Bine(int n)
{
return (int)(Math.Pow(PHI, n) / SQRT5 + 0.5);
}
static long[] NumbersFibonacci = new long[35];
public static void Iteracii(int n)
{
NumbersFibonacci[0] = 0;
NumbersFibonacci[1] = 1;
for (int i = 1; i < n - 1; i++)
{
NumbersFibonacci[i + 1] = NumbersFibonacci[i] + NumbersFibonacci[i - 1];
}
}
The time of the algorithms
If arithmetic operations are assumed to be O(1) then using Binet's formula is O(1) and the typical iterative implementation is O(n).
However, if we assume arithmetic operations are O(1) then, even though fibo(n) is a common interview and phone screen topic, it actually makes little sense to implement it in the typical way -- barring being told we are to ignore the finiteness of standard programming language integers and floating point numbers. The Fibonacci numbers grow exponentially. They overflow standard programming language types long before the particular algorithm chosen matters, as long as that is one did not choose the naive recursive implementation.
To get specific, here are two implementations of returning the nth Fibonacci numbers in C#. The top one implements Binet’s closed form solution on doubles and casts to a long, which in C# will be 64 bits wide. The second one is the iterative version:
static long constant_time_fibo(long n)
{
double sqrt_of_five = Math.Sqrt(5.0);
return (long) (
(Math.Pow(1.0 + sqrt_of_five, n) - Math.Pow(1.0 - sqrt_of_five, n)) /
(sqrt_of_five * Math.Pow(2.0, n))
);
}
static long linear_time_fibo(long n)
{
long previous = 0;
long current = 1;
for (int i = 1; i < n; i++)
{
long temp = current;
current = previous + current;
previous = temp;
}
return current;
}
static void Main(string[] args)
{
for (int i = 1; i < 100; i++)
Console.WriteLine("{0} => {1} {2}", i,
constant_time_fibo(i), linear_time_fibo(i) );
}
when I run this code I get the constant time algorithm failing to match the iterative implementation at around n = 72 due to floating point error and the iterative approach failing at n = 92 due to overflow. If I had used 32 bit types instead of 64 bits this would have happened even sooner.
Ninety-two items is nothing. If you need the nth fibonacci number in practice and only care about fibonacci numbers that fit in 64 bits, in a non-contrived situation -- not for a homework assignment or for a whiteboard question -- it should take O(1) time not because of the existence of Binet's formula but because you should use a lookup table with 92 items in it. In C++ you could even generate the 92 items at compile time with a constexpr function.
If on the other hand if we are talking about arbitrarily large number arithmetic then the question is somewhat more interesting. The exponents in Binet’s formula are all integers. You can implement Binet’s formula using only arbitrarily large integer arithmetic — you do not need to compute any square roots of 5, just need to keep track of “where the square roots of five are” because they are going to cancel out in the end. You calculate in terms of a binomial form like (a+b√5)/c but because of the weird algebraic properties of ϕ all of the irrationality and all of the non-integer math cancels out by magic. You do not need to actually calculate any √5's while finding ϕ^n. If you use “exponentiation by squaring” this will lead to an O(log n) implementation -- O(log n) arithmetic operations anyway; the time complexity of the whole thing would depend on the time complexity of the arbitrary large arithmetic library you are using.

Get separate digits from int in C# [duplicate]

This question already has answers here:
Is there an easy way to turn an int into an array of ints of each digit?
(11 answers)
Closed 5 years ago.
I stumbled across this challenge when I needed to calculate a check number/digit from the individual digits of the number itself.
E.g. I have the number (Int32) 423594340 and I want a collection of integers like 4,2,3,5,9,4,3,0.
I think it is better to not convert the given int into a String because of performance.
But how do you do that instead?
I came up with an individual puzzled out solution.
#1: Own created solution
public static IEnumerable<int> GetDigits(int source)
{
int individualFactor = 0;
int tennerFactor = Convert.ToInt32(Math.Pow(10, source.ToString().Length));
do
{
source -= tennerFactor * individualFactor;
tennerFactor /= 10;
individualFactor = source / tennerFactor;
yield return individualFactor;
} while (tennerFactor > 1);
}
#2: Modulo with Linq's .Reverse()
After that I explored the Internet for other solutions and I came across one from the Java folks: How to get the separate digits of an int number?
The downside is that the order of integers in the collection is reversed. Here comes Microsoft's Linq.
How to call the method with .Reverse().
...
GetDigits2(input).Reverse()
...
And the actual method.
public static IEnumerable<int> GetDigits2(int source)
{
while (source > 0)
{
var digit = source % 10;
source /= 10;
yield return digit;
}
}
#3: Modulo with Stack's LIFO
What else could I do when I do not want to think about calling .Revers() after the method (GetDigits2(int source))? So I use a variable inside the method, call .Reverse() on the variable and return its result instead.
Or something totally different: I remember the LIFO logic. In .NET you use the Stack class for that.
public static IEnumerable<int> GetDigits3(int source)
{
Stack<int> digits = new Stack<int>();
while (source > 0)
{
var digit = source % 10;
source /= 10;
digits.Push(digit);
}
return digits;
}
Testing
I tested each method 10 million times and measured the number of tickes between start and end of the test.
#1: Own Created method
1'549'084 ticks
#2: Modulo with Linq's .Reverse()
2'252'875 ticks
#3: Modulo with Stack's LIFO
23'626'839 ticks
tl;dr
Here comes the fiddle: Get Digits from int

C# logic (solution needed in coding) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to use as loop like : Example
i putted in textbox 123 and 300 in my formula.
1/2*(300+123/300) = 150.205 >> answer
i want to loop this Example i got answer 150.205 next formula should be look like this
1/2*(150.205+123/150.205) = 75.512
the answer of this equation i want to put in next formula by loop.
i have written code but i don't know how to use it via loop
My code.
double value = (0.5 * (300 + 123 / 300));
=======================================
For End loop
When condition match like this
1/2*(11.091+123/11.091) = 11.091
Meaning Answer and input where i m putting 300 will be same i want to break loop
**Example** I want to do this without using square root function in c#
like simple if i want a root of 9 it will be 3 so it will be like this .
i choosen 1 Because 9 is one value so i choosen 1
1/2*(1+9/1) = 5.000
1/2*(5+9/5) = 3.400
1/2*(3.4+9/3.4) = 3.024
1/2*(3.024+9/3.024) = 3.000
1/2*(3+9/3) = 3.000
see you will get same value in one point always
The only tricky thing here is a comparison with tolerance, since because of round up errors you can well never meet
answer == value
condition. The implementation could be
double answer = 300.0;
double tolerance = 1e-10;
while (true) {
// based on previous answer we compute next one
double value = 0.5 * (answer + 123.0 / answer);
//TODO: you can print out steps here, if you want something like this
//Console.WriteLine(value);
// check convergence with tolerance
if (Math.Abs(answer - value) <= tolerance) {
answer = value;
break;
}
// next answer (value) becomes the previous one (answer)
answer = value;
}
// 11.0905365064094
Console.Write(answer);
The actual answer (prove it) is just a square root:
// 11.09053650640941716205160010261...
Console.Write(Math.Sqrt(123));
Real life implementation (if my boss wants me to implement it):
public static double NewtonEstimation(Func<double, double> function,
double tolerance = 1e-10,
double guess = 1.0) {
if (null == function)
throw new ArgumentNullException("function");
else if (tolerance < 0)
throw new ArgumentOutOfRangeException("tolerance", "tolerance must not be negative");
while (true) {
double value = function(guess);
if (Math.Abs(value - guess) <= tolerance)
return value;
guess = value;
}
}
...
// 11.0905365064094
Console.Write(NewtonEstimation(x => 0.5 * (x + 123 / x)));

Inversing integers and printing it in console [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have an array of integers, which have to be converted into its inverses, so that, my program reads a series of integers from a user, fills an array with it, and then print it's inverses in a writeline. I had an idea to put inversed integers into double array, but still I don't know how to inverse (so that it looks like that - 1/N) it.
Finally, inversed integers should be printed in WriteLines.
You can use double inverse = 1.0 / number
If I understand correctly, this should work:
int arrayOfIntegers[] = <Your Array of Integers>;
foreach (input in arrayOfIntegers){
Console.WriteLine(1.0 / (double)in);
}
for(int i = 0; i < numbers.Length(); i++)
{
Console.WriteLine("1 / " + numbers[i].ToString());
}
or the foreach version:
foreach(int i in numbers)
{
Console.WriteLine("1 / " + i.ToString());
}
or to get cute:
foreach(int i in numbers)
{
Console.WriteLine("1 / {0} = {1}", i, 1.0 / i);
}
Of course this is a very basic exercise, I would like to introduce LINQ to you:
var output = yourArray.Select(x=> {
float f = 1f/x;
Console.Write(((decimal)f) + " ");
return f;
}).ToArray();
//This way you can still store the array while print all the inversed elements

Categories