Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace SoftUni_HomeWork_1_2
- {
- class Program
- {
- const uint ARRAY_SIZE = 2;
- /// <summary>
- /// Check if a given number is a fibonacci number and returns its index in the sequence
- /// </summary>
- /// <param name="number">Number to be checked</param>
- /// <returns>-1 if the number is not part of the fibonacci sequence or the index of the number in the sequence</returns>
- static int Fibonacci(uint number)
- {
- //Uses a closed form solution for the fibonacci number calculation.
- //http://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression
- double fi = (1 + Math.Sqrt(5)) / 2.0; //Golden ratio
- int n = (int)Math.Floor(Math.Log(number * Math.Sqrt(5) + 0.5, fi)); //Find's the index (n) of the given number in the fibonacci sequence
- int actualFibonacciNumber = (int)Math.Floor(Math.Pow(fi, n) / Math.Sqrt(5) + 0.5); //Finds the actual number corresponding to given index (n)
- if (actualFibonacciNumber == number)
- {
- return n;
- }
- else
- {
- return -1;
- }
- }
- /// <summary>
- /// This method tests if a given is Prime. Function is not optimized!
- /// </summary>
- /// <param name="number"> The number to be checked</param>
- /// <returns></returns>
- static bool PrimeCheck(uint number)
- {
- // Get the divisors smaller than the square root of the number
- uint divisors = (uint)Math.Sqrt(number);
- // Check if the number can be devided by any of the integer numbers smaller than its square root
- for (int cnt = 2; cnt <= divisors; cnt++)
- {
- if (number % cnt == 0)
- {
- return false;
- }
- }
- return true;
- }
- static void Main(string[] args)
- {
- uint number = 1; // Use it to store the current value
- uint[] number_of_primes = new uint[] { 24, 101, 251 }; // This array stores the numbers of the primes asked in the task
- uint counter = 1; // Counter variable used to itterate in the loop
- while (counter <= number_of_primes[ARRAY_SIZE])
- {
- if (Program.PrimeCheck(++number)) // Increment the number and check if it's a prime number
- {
- if (number_of_primes.Contains(counter)) // Output the value of the prime number if it's contained in the array
- {
- Console.Write(counter.ToString() + ": " + number.ToString());
- int index = Fibonacci(number); // Check if the number is part of the fibonacci sequence
- if (index != -1)
- {
- Console.Write(" is a fibonacci number with index: " + index.ToString() + '\n');
- }
- else
- {
- Console.Write('\n');
- }
- }
- counter++;
- }
- }
- Console.ReadKey();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement