gpt4 book ai didi

c++ - 谢尔宾斯基三角形的周长

转载 作者:太空宇宙 更新时间:2023-11-03 10:42:39 25 4
gpt4 key购买 nike

我目前正在做 this problem供自己练习。我设法通过了所有测试用例,所以我不知道出了什么问题。我的代码是:

#include <iomanip>
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
using namespace std;
int main(){
int num = 1;

while(true){
string line,stringRes;
getline(cin,line);
if(cin.eof()){break;}
long double shrinks = atof(line.c_str());

long double triangels = pow(3,shrinks);
long double length = 3/pow(2,shrinks);
long double res = floor(triangels* length * 3);
int i = 0;
while(res >= 10){
i++;
res = res/10;
};
if(shrinks == 1){
printf("Case %d: %d\n",num ,1);
}else{
printf("Case %d: %d\n",num ,i+1);
}
num++;
}
return 0;
}

例如,当我输入 1000 时,我得到 178,输入 10000 时,我得到 1762。

输入样本

0
1
5
10
100

输出样本

Case 1: 1
Case 2: 1
Case 3: 2
Case 4: 3
Case 5: 19

对于每个案例,显示案例编号,后跟表示给定迭代次数的圆周整数部分所需的小数位数。遵循示例输出的格式。

最佳答案

如前所述,您得到错误结果的原因是:使用 pow 会溢出,而且还因为您 - 正如您似乎已经意识到的那样 - 使用 3 作为起始边长。

这是一个替代的、正确的解决方案,它更短一些(没有溢出):

n >= 0 阶 Sierpinski 三角形的周长(或周长)P(n) 可以显示为:

P(n) = 3^(n + 1) / 2^n

我不提供证据,因为它不是解决问题的必要条件。但是,很容易理解必须是这种情况。一种方法是计算 Sierpinski 三角形前几阶的周长:39/227/481/8, ..., 另一个是考虑当你 (1) 将形状“缩小”½ 和 (2) 将三角形“扩展”一个因子时周长如何变化3.

任何自然数(以 10 为底)x 中的位数 D(x) 是:

D(x) = 1 + floor(log10(x))

因此,为了计算 n 阶谢尔宾斯基周长中的小数位数,我们计算 P(n) = 3^(n + 1 )/2^n,即D(floor(P(n))),这也是问题的解:

D(floor(P(n))) = 1 + floor(log10(3^(n + 1) / 2^n)) = /log(a/b) = log(a) - log(b)/ =
= 1 + floor(log10(3^(n + 1)) - log10(2^n)) = /log10(a^b) = b * log10(a)/ =
= 1 + floor((n + 1) * log10(3) - n * log10(2))

解决问题的C++实现:

/** Calculates the number of digits in the integer part of the perimeter of the Sierpinski triangle of order n */
/** Author: Fredrik Präntare, Date: 19/3/2016 */
#include <iostream>
#include <algorithm> // log10, floor
using namespace std;

int main(){
int c = 1, n;
while(scanf("%d", &n) != EOF){
int D_p = 1 + floor((n + 1) * log10(3) - n * log10(2));
printf("Case %d: %d\n", c, D_p);
c++;
}
}

关于c++ - 谢尔宾斯基三角形的周长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31387024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com