I'm trying to solve this problem without use pow()
.
I already do 1+2+3+4...+N, and 1+2²+3²..+N², but it looks impossible to solve exactly 1+2²+3³+4⁴...+NN
Can anybody help me?
Code Below:
int i = 1, sum = 0, n;
printf("Number: ", &n)
while (i <= n) {
sum = sum + i
i = i + 1
}
printf("Sum is: ", sum)
//I can't do more
This code calculates the sum of 1+2²+3³+4⁴...
, I put n=10
for simplicity
#include <stdio.h>
int main(int argc, char *argv[]) {
int i = 1, j, n = 10;
unsigned long long sum = 0;
unsigned long long nextp;
while (i <= n) {
nextp = 1;
j = 1;
while (j <= i) {
nextp *= i;
j++;
}
sum += nextp;
i++;
}
printf("%llu\n", sum);
}
Here a version that uses separate functions to make the code more modular.
It also uses for
loops instead of while
ones, since I find it more natural in this case.
n
is hard coded to 3
as an example.
#include <stdio.h>
int IntPow(int base, int exp)
{
int result = 1;
for (int i=0; i<exp; ++i)
{
result *= base;
}
return result;
}
int SumOfPows(int n)
{
int sum = 0;
for (int i=1; i<=n; ++i)
{
sum += IntPow(i,i);
}
return sum;
}
int main()
{
int n = 3;
printf("sum: %d \n", SumOfPows(n));
}
Output:
sum: 32
Live demo 1
Note:
Instead of int
s you can use larger integral types. They can also be unsigned
(like uint64_t
, assuming int
is 32 bit) in case you need to support larger values.
I assumed that the purpose of this question is to get a solution using any kind of loop, and as I mentioned above I think for
loops suit it best.
But if it must be while
loop, here's a similar solution using only while
:
#include <stdio.h>
int IntPow(int base, int exp)
{
int result = 1;
int i=0;
while (i<exp)
{
result *= base;
++i;
}
return result;
}
int SumOfPows(int n)
{
int sum = 0;
int i=1;
while (i<=n)
{
sum += IntPow(i,i);
++i;
}
return sum;
}
int main()
{
int n = 3;
printf("sum: %d \n", SumOfPows(n));
}
Output:
sum: 32
Live demo 2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With