题目描述:一个正整数有可能可以被表示为n(n>=2)个连续正整数之和,如:
15=1+2+3+4+5
15=4+5+6
15=7+8
请编写程序,根据输入的任何一个正整数,找出符合这种要求的所有连续正整数序列。
输入数据:一个正整数,以命令行参数的形式提供给程序。
输出数据:在标准输出上打印出符合题目描述的全部正整数序列,每行一个序列,每个序列都从该序列的最小正整数开始、以从小到大的顺序打印。如果结果有多个序列,按各序列的最小正整数的大小从小到大打印各序列。此外,序列不允许重复,序列内的整数用一个空格分隔。如果没有符合要求的序列,输出“NONE”。
例如,对于15,其输出结果是:
1 2 3 4 5
4 5 6
7 8
对于16,其输出结果是:
NONE
java实现:
import java.util.Scanner;
public class FindNumber {
public static void OddNumber(float m ,int
n){
boolean isWrite = false;
for(;n>1;n--){
int
checkResult = checkNumber(m,n);
switch
(checkResult){
case 0:
{
//System.out.println("--------------------There
exist numbers when n="+n+"--------------------");
int
count = n/2;
for(int
i = 0; i < n; i++){
if(i==n-1){
System.out.println((int)m/n-count+"\t");
count--;
}
else{
System.out.print((int)m/n-count+"\t");
count--;
}
}
isWrite =
true;
break;
}
case 1:
{
//System.out.println("--------------------There
exist numbers when n="+n+"--------------------");
int
count = n/2;
for(int
i = 0; i < n; i++){
if(i==n-1){
System.out.println((int)m/n-count+1+"\t");
count--;
}
else{
System.out.print((int)m/n-count+1+"\t");
count--;
}
}
isWrite
= true;
break;
}
default:{}
}
}
if(!isWrite)
{
System.out.println("NONE");
}
}
public static void EvenNumber(float m ,int
n){
boolean isWrite = false;
for(;n>1;n--){
int
checkResult = checkNumber(m,n);
switch
(checkResult){
case 0:
{
//System.out.println("--------------------There
exist numbers when n="+n+"--------------------");
break;
}
case 1:
{
int
count = n/2;
if(n
== 2){
break;
}
for(int
i = 0; i < n; i++){
if(i==n-1){
System.out.println((int)m/n-count+1+"\t");
count--;
}
else{
System.out.print((int)m/n-count+1+"\t");
count--;
}
}
isWrite
= true;
break;
}
default:{}
}
}
if(!isWrite)
{
System.out.println("NONE");
}
}
public static int checkNumber(float m ,int
n){
float fShang = m/n;
int iShang = (int) (m/n);
double iCha = fShang -
iShang;
if(iCha ==0){
//System.out.println(m+"/"+n+"\tequal\t"+fShang+"\ttrue");
return 0;//
有解
}
if(iCha == 0.5){
//System.out.println(m+"/"+n+"\tequal\t"+fShang+"\ttrue");
return
1;//有解
}
else{
//System.out.println(m+"/"+n+"\tequal\t"+fShang+"\tfalse");
return
2;//无解
}
}
public static void main(String[] args) {
// TODO Auto-generated method
stub
System.out.println("Please input a
number");
Scanner scanner = new Scanner(System.in);
float inputNumber = scanner.nextFloat();
int flag = (int)
(Math.sqrt(0.25+2*inputNumber)-0.5);
if(inputNumber%2 == 0){
System.out.println("U enter an
Even Number:"+(int)inputNumber);
EvenNumber(inputNumber,flag);
}
else{
System.out.println("U enter an
Odd Number:"+(int)inputNumber);
OddNumber(inputNumber,flag);
}
}
}