sách gpt4 ai đã đi

algorithm - Google Code Jam 2008 第 1A 轮第 3 题

In lại 作者:塔克拉玛干 更新时间:2023-11-03 04:47:36 29 4
mua khóa gpt4 Nike

problem statement在 google codejam 2008:第 1A 轮问题 3

In this problem, you have to find the last three digits before the decimal point for the number (3 + √5)N.

For example, when n = 5, (3 + √5)5 = 3935.73982... The answer is 935.

For n = 2, (3 + √5)2 = 27.4164079... The answer is 027.

我的解决方案基于 T(i) = 6*T(i-1) - 4*T(n-2) + 1 的想法,其中 T(i) 是 n=i 的整数部分,如下所示下面:

#include 
int a[5000];
chủ yếu(){
unsigned long l,n;
int i,t;
a[0]=1;
a[1]=5;
freopen("C-small-practice.in","r",stdin);
scanf("%d",&t);
for(i=2;i<5000;i++)
a[i]=(6*a[i-1]-4*a[i-2]+10001)%1000;
i=t;
for(i=1;i<=t;i++){

scanf("%ld",&n);
printf("Case #%d: %.3d\n",i,a[(int)n]);
}
fclose(stdin);
}

hiện hữu a[i]=(6*a[i-1]-4*a[i-2]+10001)%1000; 行中我知道会有整数溢出,但我不知道为什么通过添加 10,000 我得到了正确的答案。我正在使用 GCC 编译器,其中 sizeof(int)=4

谁能解释一下发生了什么?

1 Câu trả lời

首先,线

a[i]=(6*a[i-1]-4*a[i-2]+10001)%1000;

实际上不应该导致任何溢出,因为您将所有先前的值保持在 1000 以下。

其次,您是否考虑过如果 6*a[i-1]-4*a[i-2]+1 为负数会发生什么情况?模数运算符不必总是返回正值;它也可以返回负值(如果你除的东西本身就是负数)。

通过添加 10000,您已确保无论先前的值是多少,该表达式的值都是正的,因此 mod 将给出正整数结果。

关于第二点的扩展,这里是 C99 规范的 6.5.5.6:

When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded. If the quotient a/b is representable, the expression (a/b)*b + a%b shall equal a.

“丢弃”一词旁边的注释指出 /“截断为零”。因此,要使第二句话为真,当 Một 为负时 a % b 的结果本身必须为负。

关于algorithm - Google Code Jam 2008 第 1A 轮第 3 题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18964204/

29 4 0
Bài viết được đề xuất: algorithm - 使用 Map/Reduce 从多个 Sets 创建 Map
Bài viết được đề xuất: java - 如何根据IP地址获取主机名?
Bài viết được đề xuất: java - Spring @Cacheable 仍然执行复杂的键
Bài viết được đề xuất: python - 插入/删除列表之间的距离
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com