Sum of digits in C# - c#

What's the fastest and easiest to read implementation of calculating the sum of digits?
I.e. Given the number: 17463 = 1 + 7 + 4 + 6 + 3 = 21

You could do it arithmetically, without using a string:
sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}

I use
int result = 17463.ToString().Sum(c => c - '0');
It uses only 1 line of code.

For integer numbers, Greg Hewgill has most of the answer, but forgets to account for the n < 0. The sum of the digits of -1234 should still be 10, not -10.
n = Math.Abs(n);
sum = 0;
while (n != 0) {
sum += n % 10;
n /= 10;
}
It the number is a floating point number, a different approach should be taken, and chaowman's solution will completely fail when it hits the decimal point.

public static int SumDigits(int value)
{
int sum = 0;
while (value != 0)
{
int rem;
value = Math.DivRem(value, 10, out rem);
sum += rem;
}
return sum;
}

int num = 12346;
int sum = 0;
for (int n = num; n > 0; sum += n % 10, n /= 10) ;

I like the chaowman's response, but would do one change
int result = 17463.ToString().Sum(c => Convert.ToInt32(c));
I'm not even sure the c - '0', syntax would work? (substracting two characters should give a character as a result I think?)
I think it's the most readable version (using of the word sum in combination with the lambda expression showing that you'll do it for every char). But indeed, I don't think it will be the fastest.

I thought I'd just post this for completion's sake:
If you need a recursive sum of digits, e.g: 17463 -> 1 + 7 + 4 + 6 + 3 = 21 -> 2 + 1 = 3
then the best solution would be
int result = input % 9;
return (result == 0 && input > 0) ? 9 : result;

int n = 17463; int sum = 0;
for (int i = n; i > 0; i = i / 10)
{
sum = sum + i % 10;
}
Console.WriteLine(sum);
Console.ReadLine();

I would suggest that the easiest to read implementation would be something like:
public int sum(int number)
{
int ret = 0;
foreach (char c in Math.Abs(number).ToString())
ret += c - '0';
return ret;
}
This works, and is quite easy to read. BTW: Convert.ToInt32('3') gives 51, not 3. Convert.ToInt32('3' - '0') gives 3.
I would assume that the fastest implementation is Greg Hewgill's arithmetric solution.

private static int getDigitSum(int ds)
{
int dssum = 0;
while (ds > 0)
{
dssum += ds % 10;
ds /= 10;
if (dssum > 9)
{
dssum -= 9;
}
}
return dssum;
}
This is to provide the sum of digits between 0-9

public static int SumDigits1(int n)
{
int sum = 0;
int rem;
while (n != 0)
{
n = Math.DivRem(n, 10, out rem);
sum += rem;
}
return sum;
}
public static int SumDigits2(int n)
{
int sum = 0;
int rem;
for (sum = 0; n != 0; sum += rem)
n = Math.DivRem(n, 10, out rem);
return sum;
}
public static int SumDigits3(int n)
{
int sum = 0;
while (n != 0)
{
sum += n % 10;
n /= 10;
}
return sum;
}
Complete code in: https://dotnetfiddle.net/lwKHyA

int j, k = 1234;
for(j=0;j+=k%10,k/=10;);

A while back, I had to find the digit sum of something. I used Muhammad Hasan Khan's code, however it kept returning the right number as a recurring decimal, i.e. when the digit sum was 4, i'd get 4.44444444444444 etc.
Hence I edited it, getting the digit sum correct each time with this code:
double a, n, sumD;
for (n = a; n > 0; sumD += n % 10, n /= 10);
int sumI = (int)Math.Floor(sumD);
where a is the number whose digit sum you want, n is a double used for this process, sumD is the digit sum in double and sumI is the digit sum in integer, so the correct digit sum.

static int SumOfDigits(int num)
{
string stringNum = num.ToString();
int sum = 0;
for (int i = 0; i < stringNum.Length; i++)
{
sum+= int.Parse(Convert.ToString(stringNum[i]));
}
return sum;
}

If one wants to perform specific operations like add odd numbers/even numbers only, add numbers with odd index/even index only, then following code suits best. In this example, I have added odd numbers from the input number.
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Please Input number");
Console.WriteLine(GetSum(Console.ReadLine()));
}
public static int GetSum(string num){
int summ = 0;
for(int i=0; i < num.Length; i++){
int currentNum;
if(int.TryParse(num[i].ToString(),out currentNum)){
if(currentNum % 2 == 1){
summ += currentNum;
}
}
}
return summ;
}
}

The simplest and easiest way would be using loops to find sum of digits.
int sum = 0;
int n = 1234;
while(n > 0)
{
sum += n%10;
n /= 10;
}

#include <stdio.h>
int main (void) {
int sum = 0;
int n;
printf("Enter ir num ");
scanf("%i", &n);
while (n > 0) {
sum += n % 10;
n /= 10;
}
printf("Sum of digits is %i\n", sum);
return 0;
}

Surprised nobody considered the Substring method. Don't know whether its more efficient or not. For anyone who knows how to use this method, its quite intuitive for cases like this.
string number = "17463";
int sum = 0;
String singleDigit = "";
for (int i = 0; i < number.Length; i++)
{
singleDigit = number.Substring(i, 1);
sum = sum + int.Parse(singleDigit);
}
Console.WriteLine(sum);
Console.ReadLine();

Related

Reorder digits in integer using C#

I want to ask how I can reorder the digits in an Int32 so they result in the biggest possible number.
Here is an example which visualizes what I am trying to do:
2927466 -> 9766422
12492771 -> 97742211
I want to perform the ordering of the digits without using the System.Linq namespace and without converting the integer into a string value.
This is what I got so far:
public static int ReorderInt32Digits(int v)
{
int n = Math.Abs(v);
int l = ((int)Math.Log10(n > 0 ? n : 1)) + 1;
int[] d = new int[l];
for (int i = 0; i < l; i++)
{
d[(l - i) - 1] = n % 10;
n /= 10;
}
if (v < 0)
d[0] *= -1;
Array.Sort(d);
Array.Reverse(d);
int h = 0;
for (int i = 0; i < d.Length; i++)
{
int index = d.Length - i - 1;
h += ((int)Math.Pow(10, index)) * d[i];
}
return h;
}
This algorithm works flawlessly but I think it is not very efficient.
I would like to know if there is a way to do the same thing more efficiently and how I could improve my algorithm.
You can use this code:
var digit = 2927466;
String.Join("", digit.ToString().ToCharArray().OrderBy(x => x));
Or
var res = String.Join("", digit.ToString().ToCharArray().OrderByDescending(x => x) );
Not that my answer may or may not be more "efficient", but when I read your code you calculated how many digits there are in your number so you can determine how large to make your array, and then you calculated how to turn your array back into a sorted integer.
It would seem to me that you would want to write your own code that did the sorting part without using built in functionality, which is what my sample does. Plus, I've added the ability to sort in ascending or descending order, which is easy to add in your code too.
UPDATED
The original algorithm sorted the digits, now it sorts the digits so that the end result is the largest or smallest depending on the second parameter passed in. However, when dealing with a negative number the second parameter is treated as opposite.
using System;
public class Program
{
public static void Main()
{
int number1 = 2927466;
int number2 = 12492771;
int number3 = -39284925;
Console.WriteLine(OrderDigits(number1, false));
Console.WriteLine(OrderDigits(number2, true));
Console.WriteLine(OrderDigits(number3, false));
}
private static int OrderDigits(int number, bool asc)
{
// Extract each digit into an array
int[] digits = new int[(int)Math.Floor(Math.Log10(Math.Abs(number)) + 1)];
for (int i = 0; i < digits.Length; i++)
{
digits[i] = number % 10;
number /= 10;
}
// Order the digits
for (int i = 0; i < digits.Length; i++)
{
for (int j = i + 1; j < digits.Length; j++)
{
if ((!asc && digits[j] > digits[i]) ||
(asc && digits[j] < digits[i]))
{
int temp = digits[i];
digits[i] = digits[j];
digits[j] = temp;
}
}
}
// Turn the array of digits back into an integer
int result = 0;
for (int i = digits.Length - 1; i >= 0; i--)
{
result += digits[i] * (int)Math.Pow(10, digits.Length - 1 - i);
}
return result;
}
}
Results:
9766422
11224779
-22345899
See working example here... https://dotnetfiddle.net/RWA4XV
public static int ReorderInt32Digits(int v)
{
var nums = Math.Abs(v).ToString().ToCharArray();
Array.Sort(nums);
bool neg = (v < 0);
if(!neg)
{
Array.Reverse(nums);
}
return int.Parse(new string(nums)) * (neg ? -1 : 1);
}
This code fragment below extracts the digits from variable v. You can modify it to store the digits in an array and sort/reverse.
int v = 2345;
while (v > 0) {
int digit = v % 10;
v = v / 10;
Console.WriteLine(digit);
}
You can use similar logic to reconstruct the number from (sorted) digits: Multiply by 10 and add next digit.
I'm posting this second answer because I think I got the most efficient algorithm of all (thanks for the help Atul) :)
void Main()
{
Console.WriteLine (ReorderInt32Digits2(2927466));
Console.WriteLine (ReorderInt32Digits2(12492771));
Console.WriteLine (ReorderInt32Digits2(-1024));
}
public static int ReorderInt32Digits2(int v)
{
bool neg = (v < 0);
int mult = neg ? -1 : 1;
int result = 0;
var counts = GetDigitCounts(v);
for (int i = 0; i < 10; i++)
{
int idx = neg ? 9 - i : i;
for (int j = 0; j < counts[idx]; j++)
{
result += idx * mult;
mult *= 10;
}
}
return result;
}
// From Atul Sikaria's answer
public static int[] GetDigitCounts(int n)
{
int v = Math.Abs(n);
var result = new int[10];
while (v > 0) {
int digit = v % 10;
v = v / 10;
result[digit]++;
}
return result;
}

Digit sum in for loop C#

I wrote I method which is suppose to recieve a nubmer from user and then check number from 0 to 1000. Then it should return all number which have digit sum equal to recieved number. So if I enter 6, it should return numbers like 6, 42, 51, 33, 123 etc. I'd really appreciate help since I've been dwelling on this for a while now.
public static double number() {
Console.WriteLine("Enter your number! ");
string enter = Console.ReadLine();
double x = Convert.ToDouble(enter);
for (int i = 0; i < 1000; i++ ) {
double r;
double sum = 0;
while (i != 0) {
r = i % 10;
i = i / 10;
sum = sum + r;
}
if (sum == x) {
Console.WriteLine(i + " ");
}
}
return(0);
}
I am aware of the fact that there is a problem with "return(0)", but I'm not completely sure what exactly it is that this should be returning.
I'd suggest trying to do something like this:
public static IEnumerable<int> number()
{
Console.WriteLine("Enter your number!");
string enter = Console.ReadLine();
int digitSum = int.Parse(enter);
foreach (var n in Enumerable.Range(0, 1000))
{
if (n.ToString().ToCharArray().Sum(c => c - '0') == digitSum)
{
yield return n;
}
}
}
When I run this and enter 6 then I get this result:
You are almost there: the only remaining problem is that you are modifying your loop counter i inside the nested while loop, which changes the workings of the outer loop.
You can fix this problem by saving a copy of i in another variable, say, in ii, and modifying it inside the while loop instead:
double r;
double sum = 0;
int ii = i;
while (ii != 0) {
r = iCopy % 10;
ii /= 10;
sum = sum + r;
}

Calculating count of numbers with average greater than x

we have a input string such as "456,678,4599,87567"
need to find the count of numbers where average of the comma separated number's digit is greater than a number x.
Here is my working program for this problem.wanted to know if any one can suggest a more optimized code or a better optimized approach to this problem.i'm using c# code
public static int test(string i2,int limit)
{
int count=0;
int i;
int len = 0;
Int32 sum;
char[] tm={'{','}'};
i2 = i2.Trim(tm);
string[] w = i2.Split(',');
len = w.Length;
while (len-- > 0)
{
i=0;
sum = 0;
while (i < w[len].Length)
{
sum += w[len][i] - '0';
i++;
}
if (sum / i >= limit)
count++;
}
return count;
}
You can use LINQ:
var result = input.Trim('{', '}')
.Split(',')
.Count(num => num.Average(ch => ch - '0') >= limit);

Integer to Integer Array 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 1 year ago.
I had to split an int "123456" each value of it to an Int[] and i have already a Solution but i dont know is there any better way :
My solution was :
public static int[] intToArray(int num){
String holder = num.ToString();
int[] numbers = new int[Holder.ToString().Length];
for(int i=0;i<numbers.length;i++){
numbers[i] = Convert.toInt32(holder.CharAt(i));
}
return numbers;
}
A simple solution using LINQ
int[] result = yourInt.ToString().Select(o=> Convert.ToInt32(o) - 48 ).ToArray()
I believe this will be better than converting back and forth. As opposed to JBSnorro´s answer I reverse after converting to an array and therefore avoid IEnumerable´s which I think will contribute to a little bit faster code. This method work for non negative numbers, so 0 will return new int[1] { 0 }.
If it should work for negative numbers, you could do a n = Math.Abs(n) but I don't think that makes sense.
Furthermore, if it should be more performant, I could create the final array to begin with by making a binary-search like combination of if-statements to determine the number of digits.
public static int[] digitArr(int n)
{
if (n == 0) return new int[1] { 0 };
var digits = new List<int>();
for (; n != 0; n /= 10)
digits.Add(n % 10);
var arr = digits.ToArray();
Array.Reverse(arr);
return arr;
}
Update 2018:
public static int numDigits(int n) {
if (n < 0) {
n = (n == Int32.MinValue) ? Int32.MaxValue : -n;
}
if (n < 10) return 1;
if (n < 100) return 2;
if (n < 1000) return 3;
if (n < 10000) return 4;
if (n < 100000) return 5;
if (n < 1000000) return 6;
if (n < 10000000) return 7;
if (n < 100000000) return 8;
if (n < 1000000000) return 9;
return 10;
}
public static int[] digitArr2(int n)
{
var result = new int[numDigits(n)];
for (int i = result.Length - 1; i >= 0; i--) {
result[i] = n % 10;
n /= 10;
}
return result;
}
int[] outarry = Array.ConvertAll(num.ToString().ToArray(), x=>(int)x);
but if you want to convert it to 1,2,3,4,5:
int[] outarry = Array.ConvertAll(num.ToString().ToArray(), x=>(int)x - 48);
I'd do it like this:
var result = new List<int>();
while (num != 0) {
result.Insert(0, num % 10);
num = num / 10;
}
return result.ToArray();
Slightly less performant but possibly more elegant is:
return num.ToString().Select(c => Convert.ToInt32(c.ToString())).ToArray();
Note that these both return 1,2,3,4,5,6 rather than 49,50,51,52,53,54 (i.e. the byte codes for the characters '1','2','3','4','5','6') as your code does. I assume this is the actual intent?
Using conversion from int to string and back probably isn't that fast. I would use the following
public static int[] ToDigitArray(int i)
{
List<int> result = new List<int>();
while (i != 0)
{
result.Add(i % 10);
i /= 10;
}
return result.Reverse().ToArray();
}
I do have to note that this only works for strictly positive integers.
EDIT:
I came up with an alternative. If performance really is an issue, this will probably be faster, although you can only be sure by checking it yourself for your specific usage and application.
public static int[] ToDigitArray(int n)
{
int[] result = new int[GetDigitArrayLength(n)];
for (int i = 0; i < result.Length; i++)
{
result[result.Length - i - 1] = n % 10;
n /= 10;
}
return result;
}
private static int GetDigitArrayLength(int n)
{
if (n == 0)
return 1;
return 1 + (int)Math.Log10(n);
}
This works when n is nonnegative.
Thanks to ASCII character table. The simple answer using LINQ above yields answer + 48.
Either
int[] result = youtInt.ToString().Select(o => Convert.ToInt32(o) - 48).ToArray();
or
int[] result = youtInt.ToString().Select(o => int.Parse(o.ToString())).ToArray();
can be used
You can do that without converting it to a string and back:
public static int[] intToArray(int num) {
List<int> numbers = new List<int>();
do {
numbers.Insert(0, num % 10);
num /= 10;
} while (num > 0);
return numbers.ToArray();
}
It only works for positive values, of course, but your original code also have that limitation.
I would convert it in the below manner
if (num == 0) return new int[1] { 0 };
var digits = new List<int>();
while (num > 0)
{
digits.Add(num % 10);
num /= 10;
}
var arr = digits.ToArray().Reverse().ToArray();
string DecimalToBase(int iDec, int numbase)
{
string strBin = "";
int[] result = new int[32];
int MaxBit = 32;
for(; iDec > 0; iDec/=numbase)
{
int rem = iDec % numbase;
result[--MaxBit] = rem;
}
for (int i=0;i<result.Length;i++)
if ((int)result.GetValue(i) >= base10)
strBin += cHexa[(int)result.GetValue(i)%base10];
else
strBin += result.GetValue(i);
strBin = strBin.TrimStart(new char[] {'0'});
return strBin;
}
int BaseToDecimal(string sBase, int numbase)
{
int dec = 0;
int b;
int iProduct=1;
string sHexa = "";
if (numbase > base10)
for (int i=0;i<cHexa.Length;i++)
sHexa += cHexa.GetValue(i).ToString();
for(int i=sBase.Length-1; i>=0; i--,iProduct *= numbase)
{
string sValue = sBase[i].ToString();
if (sValue.IndexOfAny(cHexa) >=0)
b=iHexaNumeric[sHexa.IndexOf(sBase[i])];
else
b= (int) sBase[i] - asciiDiff;
dec += (b * iProduct);
}
return dec;
}
i had similar requirement .. i took from many good ideas, and added a couple missing pieces .. where many folks weren’t handling zero or negative values. this is what i came up with:
public static int[] DigitsFromInteger(int n)
{
int _n = Math.Abs(n);
int length = ((int)Math.Log10(_n > 0 ? _n : 1)) + 1;
int[] digits = new int[length];
for (int i = 0; i < length; i++)
{
digits[(length - i) - 1] = _n % 10 * ((i == (length - 1) && n < 0) ? -1 : 1);
_n /= 10;
}
return digits;
}
i think this is pretty clean .. although, it is true we're doing a conditional check and several extraneous calculations with each iteration .. while i think they’re nominal in this case, you could optimize a step further this way:
public static int[] DigitsFromInteger(int n)
{
int _n = Math.Abs(n);
int length = ((int)Math.Log10(_n > 0 ? _n : 1)) + 1;
int[] digits = new int[length];
for (int i = 0; i < length; i++)
{
//digits[(length - i) - 1] = _n % 10 * ((i == (length - 1) && n < 0) ? -1 : 1);
digits[(length - i) - 1] = _n % 10;
_n /= 10;
}
if (n < 0)
digits[0] *= -1;
return digits;
}
A slightly more concise way to do MarkXA's one-line version:
int[] result = n.ToString().Select(c => (int)Char.GetNumericValue(c)).ToArray();
GetNumericValue returns the visible number in your char as a double, so if your string is "12345", it will return the doubles 1,2,3,4,5, which can each be cast to an int. Note that using Convert.ToInt32 on a char in C# returns the ASCII code, so you would get 49,50,51,52,53. This can understandably lead to a mistake.
Here is a Good Solution for Convert Your Integer into Array i.e:
int a= 5478 into int[]
There is no issue if You Have a String and You want to convert a String into integer Array for example
string str=4561; //Convert into
array[0]=4;
array[1]=5;
array[2]=6;
array[3]=7;
Note: The Number of zero (0) in devider are Equal to the Length of input and Set Your Array Length According to Your input length
Now Check the Coding:
string str=4587;
int value = Convert.ToInt32(str);
int[] arr = new int[4];
int devider = 10000;
for (int i = 0; i < str.Length; i++)
{
int m = 0;
devider /= 10;
arr[i] = value / devider;
m = value / devider;
value -= (m * devider);
}
private static int[] ConvertIntToArray(int variable)
{
string converter = "" + variable;
int[] convertedArray = new int[converter.Length];
for (int i=0; i < convertedArray.Length;i++) //it can be also converter.Length
{
convertedArray[i] = int.Parse(converter.Substring(i, 1));
}
return convertedArray;
}
We get int via using method. Then, convert it to string immediately (123456->"123456"). We have a string called converter and carry to int value. Our string have a string.Length, especially same length of int so, we create an array called convertedArray that we have the length, that is converter(string) length. Then, we get in the loop where we are convert the string to int one by one via using string.Substring(i,1), and assign the value convertedArray[i]. Then, return the convertedArray.At the main or any method you can easily call the method.
public static int[] intToArray(int num)
{
num = Math.Abs(num);
int length = num.ToString().Length;
int[] arr = new int[length];
do
{
arr[--length] = num % 10;
num /= 10;
} while (num != 0);
return arr;
}
Dividing by system base (decimal in this case) removes the right most digit, and we get that digit by remainder operator. We keep repeating until we end up with a zero. Each time a digit is removed it will be stored in an array starting from the end of the array and backward to avoid the need of revering the array at the end. The Math.Abs() function is to handle the negative input, also the array is instantiated with the same size as input length.
Integer or Long to Integer Array C#
Convert it to char array and subtract 48.
public static int[] IntToArray(int value, int length)
{
char[] charArray = new char[length];
charArray = value.ToString().ToCharArray();
int[] intArray = new int[length];
for (int i = 0; i < intArray.Length; i++)
{
intArray[i] = charArray[i] - 48;
}
return intArray;
}
public static int[] LongToIntArray(long value, int length)
{
char[] charArray = new char[length];
charArray = value.ToString().ToCharArray();
int[] intArray = new int[length];
for (int i = 0; i < intArray.Length; i++)
{
intArray[i] = charArray[i] - 48;
}
return intArray;
}

C# fibonacci function returning errors

I am practising a C# console application, and I am trying to get the function to verify if the number appears in a fibonacci series or not but I'm getting errors.
What I did was:
class Program
{
static void Main(string[] args)
{
System.Console.WriteLine(isFibonacci(20));
}
static int isFibonacci(int n)
{
int[] fib = new int[100];
fib[0] = 1;
fib[1] = 1;
for (int i = 2; i <= 100; i++)
{
fib[i] = fib[i - 1] + fib[i - 2];
if (n == fib[i])
{
return 1;
}
}
return 0;
}
}
Can anybody tell me what am I doing wrong here?
Here's a fun solution using an infinite iterator block:
IEnumerable<int> Fibonacci()
{
int n1 = 0;
int n2 = 1;
yield return 1;
while (true)
{
int n = n1 + n2;
n1 = n2;
n2 = n;
yield return n;
}
}
bool isFibonacci(int n)
{
foreach (int f in Fibonacci())
{
if (f > n) return false;
if (f == n) return true;
}
}
I actually really like this kind of Fibonacci implementation vs the tradition recursive solution, because it keeps the work used to complete a term available to complete the next. The traditional recursive solution duplicates some work, because it needs two recursive calls each term.
The problem lies in <= the following statement:
for (int i = 2; i <= 100; i++)
more to the point the =. There is no fib[100] (C# zero counts) so when you check on i=100 you get an exception.
the proper statement should be
for (int i = 2; i < 100; i++)
or even better
for (int i = 2; i < fib.Length; i++)
And here is a solution that beats all of yours!
Because, why iteration when you have smart mathematicians doing closed-form solutions for you? :)
static bool IsFibonacci(int 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)
return actualFibonacciNumber == number;
}
Well, for starters your array is only 10 long and you're filling it with ~100 items (out-of-range-exception) - but there are better ways to do this...
for example, using this post:
long val = ...
bool isFib = Fibonacci().TakeWhile(x => x <= val).Last() == val;
int[] fib = new int[10];
for (int i = 2; i <= *100*; i++)
You're going out of the bounds of your array because your loop conditional is too large. A more traditional approach would be to bound the loop by the size of the array:
for (int i = 2; i < fib.Length; i++)
And make your array bigger, but as Marc said, there are better ways to do this, and I would advise you spend some time reading the wikipedia article on Fibonacci numbers.
One thing you can do is check for an early exit. Since you're trying to determine if a given number is in the Fibonacci sequence, you can do bounds checking to exit early.
Example:
static bool isFibonacci(int n)
{
int[] fib = new int[100];
fib[0] = 1;
fib[1] = 1;
for (int i = 2; i <= fib.Length; i++)
{
fib[i] = fib[i - 1] + fib[i - 2];
if (n == fib[i])
{
return true;
}
else if (n < fib[i])
{
return false; //your number has been surpassed in the fib seq
}
}
return false;
}
public static int FibNo(int n) {
int result = 0; int No = 0; int N1 = 1;
if (n< 0)
{ throw new ArguementException("number must be a positive value"); }
if (n <= 1)
{ result = n; return result; }
for(int x=1; x < n; x++)
{ result = No + N1; No = N1; N1=result; }
return result;
}

Categories