Advertisement
Guest User

Fibonacci Numbers

a guest
Apr 16th, 2015
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.55 KB | None | 0 0
  1. // Problem 10. Fibonacci Numbers
  2.  
  3. /* Write a program that reads a number n
  4.  * and prints on the console the first n members
  5.  * of the Fibonacci sequence
  6.  * (at a single line, separated by comma and space - ,):
  7.  * 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ….
  8. Note: You may need to learn how to use loops.
  9.  */
  10.  
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Linq;
  14.  
  15. class FibonacciNumbers
  16. {
  17.     static void Main()
  18.     {
  19.  
  20.         //declarations
  21.         long n;
  22.         string intro = "This program reads a number n and prints on the console the first n members\n" +
  23.         "of the Fibonacci sequence, using the formula: F_n = (phi^n - (1 - phi)^n) / sqrt(5)\n";
  24.  
  25.         string output = "\nThe first {0} members of the Fibonacci sequence are:\n{1}\n";
  26.  
  27.         double phi = (1 + Math.Sqrt(5)) / 2; // formula for phi (the golden ratio)
  28.  
  29.         //user input
  30.         Console.WriteLine(intro);
  31.  
  32.         do // validates input for n
  33.             Console.Write(@"Please, enter an integer value >= 0 and <= 74
  34. (longer sequences will produce values which cannot be stored into a type long number): ");
  35.         while (!long.TryParse(Console.ReadLine(), out n) || n <= 0);
  36.  
  37.         double[] nums = new double[n];
  38.  
  39.         //logic - calculates sequence [0:n], and stores it into the 'nums' array
  40.         for (int i = 0; i < n; i++)
  41.             nums[i] = Math.Round((Math.Pow(phi, i) - Math.Pow((1 - phi), i)) / Math.Sqrt(5));
  42.  
  43.         // prints sequence
  44.         Console.WriteLine(output, n, string.Join(", ", nums));
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement