gpt4 book ai didi

c - 七大盗&钻石之谜C程序

转载 作者:行者123 更新时间:2023-12-01 13:51:35 24 4
gpt4 key购买 nike

我最近为以下“七大盗和钻石”谜题编写了一个 C 程序:

“有七个小偷,他们从一个钻石商人那里偷了钻石,然后在丛林中逃跑。在逃跑的过程中,夜幕降临了,他们决定在丛林中休息当每个人都在 sleep 时,两个最好的 friend 起床并决定在他们之间分配钻石然后逃跑。所以他们开始分发但发现多了一颗钻石。所以他们决定唤醒第三个并再次分配钻石......但令他们惊讶的是他们仍然发现多了一颗钻石。所以他们“决定唤醒第四个。又是一颗钻石是多余的。第五个醒来……还多一颗。第六个还是多一颗。现在他们醒来第七个,钻石平均分配。”

虽然逻辑很容易理解,但我的程序似乎有很多错误。它似乎只运行数字 3、5 和 7。

总体来说我是编程新手,感觉自己的程序不是很复杂:

#include<stdio.h> 

int main()
{
int n,i,j,k;
int a[30];
printf("Enter the number of thieves\n");
scanf("%d",&n);
i=n+1;
while(1)
{
j=2;
k=0;
while(j<n)
{
if(i%j == 1 && i%n==0)
{
a[k]=1;
}
else
{
a[k]=0;
}
if(k==n-2)
{
k=0;
}
j++;
k++;
}
for(j=0;j<n-1;j++)
{
if(a[j]==0)
{
break;
}
else if(j==n-3 && a[j] == 1)
{
printf("The number of diamonds = %d\n",i);
return;
}
}
i++;
}
}

如果有人可以帮助我将这段代码开发成更非特定的东西,这样它就可以返回所有“n”值的输出,那就太好了。此外,任何反馈一般将不胜感激。

最佳答案

你的代码很难理解,所以我写了自己的代码来调试这个和你的程序,虽然晦涩难懂,但对于有效输入来说是完全正确的,你只是没有很好地处理所有情况,所以你在一个 while 循环永远。并非每个输入都适用于此问题,只有质数 会为您提供此问题的答案,因此像 2、4 和 6 这样的输入将不起作用,因此需要对其进行处理。

这是一个测试,将您的输出与我为有效输入编写的测试进行比较。

#Of Theives   Your Code    Test Code    3            3            3    5            25           25    7            301          301    11           25201        25201    13           83161        83161

You can write a quick function to test for this care of this like this:

int isPrime(int tmp)
{
int i;
for(i = 2; i <= tmp/2; i++)
{
if(tmp % i == 0)
return 0;
}
return 1;
}

然后你可以检查大于 1 的有效输入(因为这样就没有足够的小偷让故事发生)和质数,如下所示:

#include<stdio.h> 

int isPrime(int tmp)
{
int i;
for(i = 2; i <= tmp/2; i++)
{
if(tmp % i == 0)
return 0;
}
return 1;
}



int main()
{
int n,i,j,k;
int a[30];
printf("Enter the number of thieves that is prime and greater than 1\n");
scanf("%d",&n);
i=n+1;
if(isPrime(n) && n > 1)
{
while(1)
{
j=2;
k=0;
while(j<n)
{
if(i%j == 1 && i%n==0)
{
a[k]=1;
}
else
{
a[k]=0;
}
if(k==n-2)
{
k=0;
}
j++;
k++;
}
for(j=0;j<n-1;j++)
{
if(a[j]==0)
{
break;
}
else if(j==n-3 && a[j] == 1)
{
printf("The number of diamonds = %d\n",i);
return;
}
}
i++;
}
}
else
{
printf("Input Invalid.\n");
}
}

我写的测试谜语的代码:

#include<stdio.h>


int isPrime(int tmp)
{
int i;
for(i = 2; i <= tmp/2; i++)
{
if(tmp % i == 0)
return 0;
}
return 1;
}

long gcd(long a, long b) {
if (b == 0) {
return a;
}
else {
return gcd(b, a % b);
}
}

int main()
{
int thieves, i;
long diamonds, lcm = 1;
printf("Enter the number of thieves that is prime and greater than 1:\n");
scanf("%d",&thieves);

if(isPrime(thieves) && thieves > 1)
{
for(i = 2;i < thieves;i++)
{
lcm = (lcm*i)/gcd(i,lcm);
}

i = 1;
dimonds = lcm*i + 1;
while(dimonds % thieves != 0)
{
dimonds = lcm*++i + 1;
}
printf("There are a minimum of diamonds is: %d\n",diamonds);
}
else
{
printf("Input inv\n");

}
}

关于c - 七大盗&钻石之谜C程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31233717/

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