Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use while to sum power like 1+2²+3³

Tags:

c

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
like image 460
Joao Torres Avatar asked Oct 19 '25 14:10

Joao Torres


2 Answers

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);

}
like image 186
sotona Avatar answered Oct 21 '25 02:10

sotona


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 ints 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

like image 44
wohlstad Avatar answered Oct 21 '25 03:10

wohlstad