public class ConsecutiveIntegerSum { public static void main(String[] args) { devideIntoConsecutiveIntegerSum(10000); } public static void devideIntoConsecutiveIntegerSum(int num){ int a1 = 1; int n = 2; for(n = 2 ; n < num ;n++){ for(a1 = 1; a1 < num ;a1++){ if((n*n + (2*a1 - 1)*n ) == 2 *num){ for(int i=1;i<=n;i++){ System.out.print((a1 + (i-1)) + ","); } System.out.println(); } } } } }
#include <stdio.h> #include <malloc.h> void devide (int *arr, int len, int num, int thr); void devide_rec (int *arr, int len, int num, int thr); void printArr (int *arr, int len) { int i = len-1; while (arr[i]) { printf ("%d ", arr[i]); i -= arr[i]; } printf ("\n"); } void devide (int *arr, int len, int num, int thr) { arr[num] = thr; num -= thr; if (!num) { printArr (arr, len); return; } devide_rec (arr, len, num, thr); } void devide_rec (int *arr, int len, int num, int thr) { int i; if (thr > num) { thr = num; } for (i = 1; i <= thr; ++i) { devide(arr, len, num, i); } } int main () { int num = 6; int *arr = (int*)malloc(sizeof(int)*(num+1)); arr[0] = 0; devide_rec (arr, num+1, num, num); free(arr); return 0; }
/* 设初始值为x,有m个数,因为是连续的数字,那么求和为mx + m*(m-1)/2 = n。 因为x至少为1,那么代入可推出m<=√(2*n),而且m>=2。然后枚举m,由等式可求出x, 如果x为整数,那么x就满足题意,可输出。效率可达到o(√n) */ #include<iostream> #include<cmath> using namespace std; void main() { int n; cin >> n; for(int m = sqrt(2*n); m >=2 ; m --) { double fx = (double)(2*n - m*(m-1)) / (2*m); int dx = (int)fx; if(dx == fx) { for(int i = dx; i < dx+m; i ++) { cout << i << " "; } cout << endl; } } }
int Fun(int n) { int m = (n+1)/2; for ( int i=2;i<=m;++i ) { if ( 0==(n-(i-1)*i/2)%i ) { return (n-(i-1)*i/2)/i); } } return -1; }
import java.util.Scanner; public class GetSum { public static void main(String[] argv){ Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); for(int i=1, startNum=1, sum=0;i<=n/2;i++){ sum += i; System.out.println("i :" + i + " startNum :" + startNum + " sum :" + sum); if(sum > n){ sum = 0; i = startNum; startNum+=1; continue; } if(sum == n){ for(int j=startNum;j<=i;j++){ System.out.print(j + " "); } System.out.println(); sum = 0; i = startNum; startNum += 1; } } } }
int input; //开始时输入的正整数,设定为全局变量 int main() { int i; input = 9; //赋值9,答案:4,5和2,3,4 for (i = 1; i < input; i++) //起始值设定为1开始往上升,直到input-1结束 calResult(0, i); return 0; } int calResult(int sum, int num) { int num_t; int sum_t; int ret=0; if (sum + num == input) //如果跟input一致就判断找到连续和跟input一致的结果 { printf("number: %d",num); return 1; } else if (sum + num > input) //如果大于input返回-1终止递归 return -1; else { sum_t = sum + num; num_t = num + 1; ret = calResult(sum_t, num_t); //使用递归查看连续累加的数值跟input比较 if (ret == 1) printf(",%d",num); return ret; } }
#include<stdio.h>
int main()
{
int i,z,x,y,j;
printf("please input z:");
scanf("%d",&z);
for(i=1;i<=z;i++)
for(x=1;x<=z;x++)
{
y=x+i-1;
if((y+x)*i==2*z)
{
for(j=x;j<=y;j++)
printf("%3d ",j);
printf("\n");
}
}
}