关于一个递归算法问题,求教
3. 一列数的规则如下: 1、1、2、3、5、8、13、21、34...... 求第30位数是多少, 用递归算法实现。
[解决办法]
[解决办法]
惭愧,还真不知道那叫斐波那契数列,学习了。我算的结果是832040
? int[] ints=new int[30];
? ints[0] = 1;
? ints[1] = 1;
? int c = 0;
? for (int i = 2; i < 30; i++)
? {
? ints[i]=ints[i-1]+ints[i-2];
? c = ints[i];
? }
? Console.WriteLine(c);
[解决办法]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 实验1
{
? class f1
? {?
? int s=0;
? public int f(int n)
? {
? if (n == 0 | n == 1)
? {
? s = 1;
? return s;
? }
? else
? {
? s = f(n - 1)+f(n - 2);
? } ?
? return s; ?
? } ?
? ?
? }
? class Program
? {
? static void Main(string[] args)
? {
? int a;
? f1 one = new f1();
? a= one.f(6);
? Console.WriteLine(a);
? ?
? }
? }
}
[解决办法]
楼主请看下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 递归
{
? class Program
? {
? static void Main(string[] args)
? {
? // 一列数的规则如下: 1、1、2、3、5、8、13、21、34...... 求第30位数是多少, 用递归算法实现。
? int n = Sum(30);
? Console.WriteLine(n);
? Console.ReadKey();
? }
? static int Sum(int num)
? {
? int sum = 1;
? for (int i = num; i >=2; i--)
? {
? sum = Sum(num - 1) + Sum(num - 2);
? }
? return sum;
? }
? }
}