简体   繁体   English

有没有办法在运行时间上优化此C程序

[英]Is there a way to optimize this C program in terms of run time

its objective is to print all Fibonacci numbers up to the 93th 它的目的是打印所有直到第93位的斐波那契数字

#include<stdio.h>

void main(){
  unsigned long long first=0,second=1,sum;
  printf("%llu,%llu",first,second);
  unsigned char hops=1;
  while (hops<93) {
    sum=first+second;
    printf(",%llu",sum);
    first=second;
    second=sum;
    hops++;
  }
  printf("\n");
}

Of course, you can. 当然可以。 Just print precalculated string of numbers. 只需打印预先计算的数字字符串即可。

#include <stdio.h>
int main()
{
    puts("0,1,1,2,3,5,...");
    return 0;
}

In case you need to optimize the whole operation you need to think in terms of space and time complexity. 如果您需要优化整个操作,则需要考虑时间和空间的复杂性。 From this point onwards you can think how better these can be. 从现在开始,您可以考虑这些方法可以做的更好。

Now printing the n numbers will ofcourse require an iteration which will be of time complexity O(n) . 现在打印n数字当然需要迭代,该迭代的时间复杂度为O(n) Is there any better way to do that? 有什么更好的方法吗? The thing is, if you do it multiple times you can get rid of addition by storing it somewhere. 关键是,如果您多次执行此操作,则可以通过将其存储在某个位置来摆脱添加。 But that won't give you any better asymtotic time complexity improvement - rather you will face a O(n) space complexity - which will be an over head if printing is something you do only. 但这不会为您带来更好的渐近时间复杂度改进-而是您将面临O(n)空间复杂度-如果仅执行打印操作,这将是头疼的事情。 (And ofcourse pre-computation have to be done). (当然,必须进行预计算)。

So yes this solution is good enough to achieve what you are trying to do. 因此,是的,此解决方案足以实现您要执行的操作。

In case you need to scan some input - then I would ask you to go for getting inputs with getchar and then form the number from it (if needed). 万一您需要扫描一些输入-那么我会要求您使用getchar获取输入,然后从中形成数字(如果需要)。 If you consider this in SPOJ or competitive programming judge server these tend to give better result. 如果您在SPOJ或竞争性编程判断服务器中考虑这一点,则这些往往会带来更好的结果。 (Again time is lesser than that of scanf in large number of input cases - 10^7 etc). (在大量输入情况下,重新开始时间比scanf短-10 ^ 7等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM