查找 "Cullen' 号的 C 代码”

标签 c

需要编写一段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/

相关文章:

c - 原始套接字不发送包含任意数据的数据包

c - 使用 -D 构建 C 代码时出错

c++ - printf ("... %c ...",'\0' ) 和家人——会发生什么?

c++ - ReadProcessMemory 更快

c - 如何使用指针复制字符串

c - malloc 内存上的 memcpy 运行不佳

c - 在处理 strcpy(string, "") 时,字符串未被正确清空和分配

c - 编译器优化会影响动态内存分配吗?

c - 使用指针取消引用生成的模糊输出?

c - 在 for 循环之后没有 {} 大括号 for (i=0; s[i]> ='0' && s[i] <= '9' ;++i)