题目:任意一个数n的3次方都可以用n个连续的奇数相加得到.例如:
1^3 = 1
2^3 = 3 + 5;
3^3 = 7 + 9 +11;
等.....
java代码:
import java.util.Scanner; public class test { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int num =sc.nextInt(); /* int arr[] = slove(num); for(int i=0;i<num;i++) System.out.println(arr[i]);*/ slove2(num); }
//方法一:
public static int [] slove(int num)
{
int arr[] = new int[num];
int sum = (int) Math.pow(num, 3);
System.out.println(sum);
int total = 0;
for(int i=1;;i=i+2)
{
int k = i;
total = 0;
for(int j = 0;j<num;j++)
{
arr[j] = k ;
total += arr[j];
k = k+2;
}
if(total == sum)
break;
}
return arr;
}
//方法二:
//n*a + n*(n-1) = sum
public static void slove2(int num)
{
int sum = (int )Math.pow(num,3);
int a = (sum - num*(num-1))/num;
for(int i=0;i<num;i++)
{
System.out.println(a);
a = a+2;
}
}
}
其实很简单的,但是我就是不仔细的读题 ,将奇数误看成素数了,所以很是吃亏,再这写下来告戒自己以后做题要仔细认真.