一个程序拿出来show show,求n的阶乘保留小数点后16位,在P41.7G下计算100万的阶乘大概是1秒。大家给点意见
// 在VC++6.0下写的
// 求n的阶乘保留小数点后16位,1.0e+300 进制
// 代码简单就不注释了,在P41.7G,256M内存下计算100万的阶乘大概是1秒
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// 读浮点数的指数
#define get_exp(p) ( atoi(p + strlen(p) - 3) )
main()
{
time_t
stime,
etime;
unsigned char
pr[50];
unsigned long int
n,
re;
unsigned long int register
i;
double
r;
while(1)
{
printf("input n [<=1.0e+8 , 0 -- exit] :");
scanf("%ld", &n); // n不是整数会死循环
if(!n)
break;
r = 1.0;
re = 0;
// 开始计算
time(&stime);
for(i = 2; i <= n; i++)
{
r = r * i;
if(r >= 1.0e+300)
{
r /= 1.0e+300;
re += 300;
}
}
time(&etime);
sprintf(pr, " %d! = %.20e", n, r);
sprintf(pr+strlen(pr)-3, "%ld", get_exp(pr)+re);
printf(" %s \n ", pr);
printf(" use time: %.4f s\n", difftime(etime, stime));
}
}
// 求n的阶乘保留小数点后16位,1.0e+300 进制
// 代码简单就不注释了,在P41.7G,256M内存下计算100万的阶乘大概是1秒
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// 读浮点数的指数
#define get_exp(p) ( atoi(p + strlen(p) - 3) )
main()
{
time_t
stime,
etime;
unsigned char
pr[50];
unsigned long int
n,
re;
unsigned long int register
i;
double
r;
while(1)
{
printf("input n [<=1.0e+8 , 0 -- exit] :");
scanf("%ld", &n); // n不是整数会死循环
if(!n)
break;
r = 1.0;
re = 0;
// 开始计算
time(&stime);
for(i = 2; i <= n; i++)
{
r = r * i;
if(r >= 1.0e+300)
{
r /= 1.0e+300;
re += 300;
}
}
time(&etime);
sprintf(pr, " %d! = %.20e", n, r);
sprintf(pr+strlen(pr)-3, "%ld", get_exp(pr)+re);
printf(" %s \n ", pr);
printf(" use time: %.4f s\n", difftime(etime, stime));
}
}
...全文
相关推荐
s2p_show.zip
描述中提到"S2P文件转化",这意味着该压缩包可能包含一个程序或脚本,能够将S2P文件转换为其他格式,便于进一步分析或使用。"
C++程序设计
* 递归函数double fun(int n1,double x),用于计算多项式的第n1项。* 函数void process(),用于完成求前n项的工作,并将它们存放到p指向的动态数组中。
python matplotlib如何给图中的点加标签
'`设置点的颜色为红色,`label='1'`定义了图例标签,`s=100`设置点的大小。
16点阵汉字库点阵显示程序
16x16点阵汉字库点阵显示程序,内含16x16的国标汉字库hzk16文件[root@jocks show1616]# ./a.out "中"// 中0x01,0x00, // 00000001000
遗传算法Python实战:N-Queen问题的工程化实现与调优
遗传算法(GA)是一种基于自然选择机制的通用随机优化方法,其核心在于模拟生物进化中的选择、交叉与变异过程,通过适应度函数引导种群向最优解演化。在实际工程中,GA的成功高度依赖于问题建模的严谨性、适应度函数的设计合理性以及早停、精英保留等关键机制的稳健实现。尤其在组合优化场景(如N-Queen问题)中,需兼顾解的合法性约束、计算效率与收敛稳定性。本文聚焦Python环境下的生产级GA落地实践,深入解析种群初始化、向量化适应度计算、防崩溃变异策略及浮点安全早停等关键技术细节,为解决调度、布局、参数寻优等真实优化


