数列的第N个项

1 , 1 , 2 , 3 , 5 , 8 , 13 ……

求此数列的第N个项

用一维数组来做:

import java.util.*;
public class shulie {
         public static void main(String[] args)
         {
                  Scanner sc = new Scanner(System.in);
                  System.out.println(“输入数字:”);
                  int n = sc.nextInt();
  
                  int[] x= new int [n];
                  for(n=0;n<x.length;n++)
                 {
                          if(n==0||n==1)
                          {
                                  x[n]=1;
                           }
                          else
                          {
                                  x[n]=x[n-2]+x[n-1];
                           }
                  }    
                  System.out.println(x[n-1]);
         }
}

用递归来做:

import java.util.*;
public class shulie {
         public static int shuzu(int n)
        {
                 int shuzi;
                 if(n==1||n==2)
                 {
                          shuzi = 1;
                  }
                 else
                  {
                           shuzi = shuzu(n-2)+shuzu(n-1);
                   }
                  return shuzi;
           }
           public static void main(String[] args)
            { 
                    Scanner sc = new Scanner(System.in);
                    System.out.println(“输入数字:”);
                     int a = sc.nextInt();
                     int x = shuzu(a);
                     System.out.println(x);
              }
}

“数列的第N个项”暂时没有评论

发表评论:

姓名 (*):
E-Mail (*):
网址:
内容 (*):
XHTML: 可用标签: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>