gpt4 book ai didi

c - 给定一个正整数,判断它是否等于四个连续整数之和

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

问题:

Given a positive integer, tell whether it is equal to the sum of four consecutive integers.

Input Format:
Input consists of a single positive integer,

Output Format:
Output consists of a string which is either "yes" or "no". Print yes when the given number is the sum of four consecutive integers and print no otherwise.

Example:
In this example, 2 = -1 + 0 + 1 + 2, and 82 = 19 + 20 + 21 + 22. 5 and 41 are not of the correct form.

Sample Input 1:
2

Sample Output 1:
yes

Sample Input 2:
41

Sample Output 2:
no

我的程序未被接受,并且对于某些值,我的结果正在重复,任何人都可以帮助我吗?

#include <stdio.h>

int main()
{
int num,sum1=0,index,sum2=0,Soln=0;
int temp,i;
scanf("%d",&num);
if(num <= 0 )
{
printf("Wrong Input\n");
return 0;
}
for(index=1;;index++)
{
sum1=sum1+index;
if(sum1>=num)
break;
}
if(sum1 == num )
{
if(num == index)
{
printf("yes");
return 0;
}
Soln++;
printf("no" );
for(temp=1;temp<=index;temp++)
printf("no");
}
for(i=1;i<index;i++)
{
sum2+=i;
if((sum1-sum2) == num )
{
if((i+1) == index)
{
//printf("yes");
break;
}
Soln++;
printf("no" );
for(temp= i+1;temp<=index;temp++)
printf("no");
break;
}
}
if( Soln == 0 && num >= 9 && num/2 == (num-1)/2 ) //--> if U don't want more than one ,soln use this
//if( num >= 9 && num/2 == (num-1)/2 ) //--> if U want more than one soln, use this
{
Soln++;
printf("no");
}
if(Soln==0)
{
printf("yes");
}
return 0 ;
}

最佳答案

取四个连续的整数 k、k+1、k+2 和 k+3 并将它们相加。得出 4k + 6。如果整数 n 是四个连续整数的和,则意味着对于某个整数 k,n = 4k + 6。等价地,这意味着对于某个整数 k,n - 6 = 4k,或者等价地 (n - 6) mod 4 = 0。这可能会帮助您显着简化您的程序。

关于c - 给定一个正整数,判断它是否等于四个连续整数之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32288343/

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