gpt4 book ai didi

查找 "Cullen' 号的 C 代码”

转载 作者:行者123 更新时间:2023-11-30 20:23:20 25 4
gpt4 key购买 nike

需要编写一段C代码,要求用户输入一个数字,该代码将检查该数字是否是“卡伦数”。

只要能通过“2^n * n + 1”计算出来的数字就是卡伦数。

卡伦数示例:

3=2^1 * 1 + 1
9=2^2 * 2 + 1
25=2^3 * 3 + 1

这是我正在编写的代码,有什么帮助吗?

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

int main(void)

{

int num, brojP, potency = 0, numRepeats = 0, endResult=0, isCullen;

printf("Unesite broj");
scanf("%d", &num);

do
{

potency = potency + 1; // initializing "potency" and at the same time making it one number larger at each repeat of the loop
do
{
brojP = 2*potency;
numRepeats = numRepeats + 1;
} while (numRepeats < potency); // this entire loop is used for "2^n" part

endResult = brojP * potency + 1; // calculate the "2^n * n + 1"
numRepeats = 0;

if (endResult == num)
{
isCullen = 1;
break;
}


} while (endResult < num);

if (isCullen == 1)
printf("Number inputted is Cullen's number\n");
else
printf("Number inputted isn't Cullen't number\n");

return 0;


}

最佳答案

这个循环是错误的:

    do
{
brojP = 2*potency;
numRepeats = numRepeats + 1;
} while (numRepeats < potency); // this entire loop is used for "2^n" part

您每次都需要将上一次迭代的结果乘以 2,但实际上是将效力乘以 2。由于效力不会改变,因此您只是一遍又一遍地执行相同的任务。这样做:

    brojP = 1;
for (numRepeats = 0; numRepeats < potency; numRepeats++) {
brojP *= 2;
}

关于查找 "Cullen' 号的 C 代码”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36344110/

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