cs1713-day1-prog4.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright (C) 2020, 2019, 2018, 2017 Girish M
  3. * This program is free software; you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation; either version 3 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program; if not, write to the Free Software
  15. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  16. * MA 02110-1301, USA.
  17. *
  18. */
  19. /*-----------------------------------
  20. Name: Girish M
  21. Roll number: cs1713
  22. Date: 25 July 2017
  23. Program description:Take a positive integer x from the user, and compute the value of x!.
  24. How long does it take with naive multiplications? Can you do any
  25. better? Can you compute for arbitrary sized inputs?
  26. Acknowledgements:http://pubs.opengroup.org/onlinepubs/7908799/xsh/regcomp.html
  27. ------------------------------------*/
  28. #include <stdio.h>
  29. /*
  30. Dynamic Programming Approach
  31. Funtion to calculate up to N Factorials
  32. */
  33. long int factorialDP(int n)
  34. {
  35. long int a[n+1],i,j; // factorials array
  36. a[0]=1;
  37. for(i=1;i<=n;i++)
  38. {
  39. a[i] = i * a[i-1];
  40. }
  41. return a[n];
  42. }
  43. int main(void)
  44. {
  45. int n, i;
  46. long int factorial = 1;
  47. printf("\nEnter a number\n");
  48. scanf("%d", &n);
  49. if(n >= 0 && n < 21)
  50. {
  51. /*Iterative logic
  52. for( i=1 ; i<=n; i++)
  53. {
  54. factorial = factorial * i;
  55. }*/
  56. printf("\nFactorial of %d is %ld.\n", n, factorialDP(n));
  57. }
  58. else
  59. {
  60. printf("\nFactorial can be computed for number from 0 to 20\n");
  61. }
  62. return 0;
  63. }