zoukankan      html  css  js  c++  java
  • sicily 6382. 公式计算

    Description

      实现以下函数:

    long my_function(int m, int n)

    用来计算下面数学式的值,并且将计算结果返回:

    图片

     

    Input

     实现函数 my_function notice:请不要改动函数头

     

    Output

     测试平台会调用你实现的函数,你只需要返回正确的计算结果即可,放回结果的规则如下:

    1, 如果平台提供的m, n  的值是不合法的,例如 m == 2, n == 1, 那么返回结果-1

    2, 如果平台调用函数是合法的,那么放回数学式的值,例如 m == 0, n == 0时,那么你的函数需要返回 1.

     

    用过两种写法AC。一种是自己平时笔算用的化简后的公式,只需要long long就能AC

    View Code
     1 long my_function(int m, int n)
     2 {
     3     long long factorial = 1;    /* the factorial of n-m */
     4     long long product = 1;        /* the product of integers from m+1 to n */
     5     int i;                        /* the counter  */
     6     
     7     /* legitimacy verification and computation begins
     8      * the algorithm is as shown in the comment above */
     9     if ( m > n || n < 0 || m < 0 )
    10     {
    11         return -1;
    12     }
    13     else if( m == n || m == 0)
    14     {
    15         return 1;
    16     }
    17     else
    18     {   
    19         for ( i = m + 1; i <= n; i++ )
    20         {
    21             product = product * i;
    22         }
    23     
    24         for ( i = 1; i <= n - m; i++ )
    25         {
    26             factorial = factorial * i;
    27         }
    28         
    29         return (long)( product / factorial ); 
    30     }
    31     /* verification and computation ends */
    32 }

    还有一种就是三个阶乘全算出来的做法,需要使用double,否则会溢出WA

    View Code
     1 long my_function(int m, int n)
     2 {
     3     double facn = 1, facm = 1, facn_m = 1;
     4     int i;
     5     
     6     if ( m > n || n < 0 || m < 0 )
     7     {
     8         return -1;
     9     }
    10     else if( m == n )
    11     {
    12         return 1;
    13     }
    14     else
    15     {   
    16         for ( i = 1; i <= m; i++ )
    17         {
    18             facm = facm * i;
    19         }
    20             
    21         for ( i = 1; i <= n; i++ )
    22         {
    23             facn = facn * i;
    24         }
    25     
    26         for ( i = 1; i <= n - m; i++ )
    27         {
    28             facn_m = facn_m * i;
    29         }
    30     
    31         return (long)( facn / ( facm * facn_m ) ); 
    32     }
    33 }

    写完还想看看有什么组合数的优化算法,结果发现这是一个巨坑,而且是一个数学巨坑,作罢……

  • 相关阅读:
    HBase入门笔记(四)完全分布式HBase集群安装配置
    is not in sudoer file
    PHP学习之八:执行运算符与字符加一
    Windows Phone 7回车键获取
    Asp.Net重定向
    WindowsPhone7开发之 Push+Notification
    Windows phone 7开发之(页面间跳转与传值)
    Windows Phone 7开发者注册Marketplace
    Windows Phone7开发之 容器控件
    Windows Phone7开发之 其他控件
  • 原文地址:https://www.cnblogs.com/joyeecheung/p/2767053.html
Copyright © 2011-2022 走看看