入门训练 Fibonacci数列

本文探讨了使用Java和C++实现同一算法的不同方法,包括递归和循环方式,并对比了它们在效率上的表现。文章通过具体示例,详细解释了每种语言的优缺点及其适用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

嗯,用java写算法还真有点不适应呢。

在这里插入图片描述

这个题其实就两种思路,递归,循环。

/*C++循环--编译成功*/
#include <iostream>
using namespace std;

int main(void) {
  long long int n, i;
  long long int result = 0;
  long long int arr[1000000];
  cin >> n;
  arr[0] = 1;
  arr[1] = 1;
  if (n == 1 || n == 2)
  {
    cout << 1 % 10007;
  }
  else if (n != 1 && n != 2)
  {
    for (i = 2; i < n; i++)
    {
      arr[i] = (arr[i - 1] + arr[i - 2]) % 10007;
      result = arr[i];
    }
    cout << result;
  }
  return 0;
}


/*java递归--超时*/

import java.util.Scanner;
public class Main {
		public static int f(int n)
		{
			int x;
			if(n == 1 || n == 2)
				return 1 % 10007;
			else 
				x = f(n - 1) + f(n - 2);
			return x;
		}
	    public static void main(String[] args) {
	    	int n;
	    Scanner a = new Scanner(System.in);
	    n = a.nextInt();
	    System.out.print(f(n) % 10007);
	        
	  
	        
	    }	
}

/*java循环 --编译成功*/
import java.util.Scanner;
public class Main{

public static void main(String[] args) {
  int n, i;
   int result = 0;
  int[] arr= new int[1000000];
 
    Scanner a = new Scanner(System.in);
  n = a.nextInt();
  arr[0] = 1;
  arr[1] = 1;
  if (n == 1 || n == 2)
  {
    System.out.print( 1 % 10007);
  }
  else if (n != 1 && n != 2)
  {
    for (i = 2; i < n; i++)
    {
      arr[i] = (arr[i - 1] + arr[i - 2]) % 10007;
      result = arr[i];
    }
    System.out.print( result);
  }
 
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Αиcíеиτеǎг

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值