using System;
using System.Linq;
namespace Fibonacci
{
class Program
{
static void Main(string[] args)
{
string number;
bool check = true;
Console.Write("Enter fibonacci sequence: ");
do
{
number = Console.ReadLine();
if (checkInputData(number))
{
Console.WriteLine("invalid number");
Console.Write("Enter again: ");
}
else
check = false;
} while (check);
if (checkFibonacci(number))
Console.WriteLine("string is fibonacci sequence");
else
Console.WriteLine("string is not fibonacci sequence");
}
// ======check input data=====
// don't accept non-numeric characters
// fibonacci must be start 0 1 or 1 1
static bool checkInputData(string number)
{
bool check = false;
string[] convert = number.Split(" ");
if(convert[0] == "0" && convert[1] != "1" || convert[0] == "1" && convert[1] != "1" || convert.Length < 3)
{
check = true;
}
else
{
for (int i = 0, intType; i < convert.Length; i++)
{
if (Int32.TryParse(convert[i], out intType) == false)
{
check = true;
break;
}
}
}
return check;
}
//====check Fibonacci========
static bool checkFibonacci(string number)
{
bool result = true;
int sum;
int[] fibonacci = number.Split().Select(int.Parse).ToArray();
for (int i = 0; i < fibonacci.Length - 2; i++)
{
sum = fibonacci[i] + fibonacci[i + 1];
if (fibonacci[i + 2] != sum)
{
result = false;
break;
}
}
return result;
}
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter