Reputation: 183
I need to write a Java program that does the following - For each of the first ten positive integers, raise them all to power 1, then find that sum. Then raise them all to power 2, and find the sum. Then raise them to power 3, and then find the sum and so on and so forth and then just print out the sums. Basically,
11 + 21 + 31 + ... + 101 = sum1
12 + 22 + 32 + ... + 102 = sum2
13 + 23 + 33 + ... + 103 = sum3
14 + 24 + 34 + ... + 104 = sum4
15 + 25 + 35 + ... + 105 = sum5
and just print out the values of sum1 to sum5.
Here's what I've tried;
public static void main(String[] args) {
for (double power=1;power<=5;power++)
{
for (double n=1;n<=10;n++)
{
double result = (Math.pow(n, power));
if (n%10==0)
{
double sum=0;
sum+=result;
System.out.println(sum);
}
}
}
}
}
I do get five outputs, but not quite the desirable ones. It just prints out
10.0
100.0
1000.0
10000.0
100000.0
How do I fix this?
Upvotes: 2
Views: 159
Reputation: 1
public class Numrat {
public static void main(String [] args) {
double sum=0;
for(int power=1; power<6; power++) {
for(int j= 1;j<11; j++) {
double variable=(Math.pow(j, power));
sum +=variable;
}
System.out.println(sum);
}
}
}
Upvotes: 0
Reputation: 298898
It's pretty easy when you use IntStream ranges:
public static void main(String[] args) {
IntStream.range(1, 6) // second param is exclusive
.map(power ->
IntStream.range(1, 11)
.map(n -> (int) Math.pow(n, power))
.sum())
.forEach(System.out::println);
}
Output:
55
385
3025
25333
220825
The heavy lifting is done by this bit:
IntStream.range(1, 11)
.map(n -> (int) Math.pow(n, power))
.sum()
it loops over the ints from 1 to 10, raises each of them to the current power, and sums them up together. The outer stream just loops over the powers and pipes the output to System.out.println()
.
Upvotes: 2
Reputation: 40048
First you don't need if
block in inner for loop which is ignoring the values other that 10
and second you just need variable in outer for
to store the result
for (double power = 1; power <= 5; power++) {
double sum = 0;
for (double n = 1; n <= 10; n++) {
double result = (Math.pow(n, power));
sum=sum+result;
}
System.out.println(sum);
}
Upvotes: 1