I hope someone is able to help me . .

Hello everyone . .

I have a problem write a function by using C++,

Function is: sum=1+2^2+3^3+4^4..+n^n .

I tried a lot but . . . ^_^

I hope someone is able to help me.


closed account (o3hC5Di1)
Hi there,

Please post some example code, then we'll go from there :)

All the best,
NwN
1
2
3
4
5
6
7
8
9
#include <cmath>

unsigned long int your_homework(unsigned long int n)
{
    if (n == 1)
        return 1;

    return std::pow(n, n) + your_homework(n - 1);
}

HI . .

I need to sum ​​this function sum=1+2^2+3^3+4^4..+n^n .

I have many solutions from friends, but they are all wrong .

first ::

1
2
3
4
5
6
7
8
9
10
#include<stdio.h>
int main()
{
	float i,n,sum;
	scanf("n=%f",&n);
	sum=0;
	for(i=1;i<n;i++)
	sum=sum+i*i;
	printf("sum=%f",sum);
}

::::::::::::::::::::::::::::::::::::::::::::::

Second ::

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <math.h>
#include<stdio.h>

int main()
{
      int sum,x,j,i;
      scanf("x=%f",&x);
      for(i=1;i<=x;i++);
      sum=x;
      scanf("j=%f",&j);
      for(i=1;i<x;i++);
      float pow( float, int );
      printf("sum=%f",sum);
      return 0;
}	

::::::::::::::::::::::::::::::::::

all wrong . . !!!
closed account (o3hC5Di1)
Hi there,

Catfish2 's solution looks quite right - what are you trying to do with scanf here? It seems to me like you don't entirely understand the usage of that function (or I'm terribly mistaken myself).

In order to use Catfish2's function your program should look as such:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <cmath>

using namespace std;

//Catfish2's function
unsigned long int your_homework(unsigned long int n)
{
    if (n == 1)
        return 1;

    return pow(n, n) + your_homework(n - 1);
}

int main()
{
    unsigned long int n, sum;
    n = 4; //replace this value for whatever you want n to be off course
    sum = your_homework(n);
    cout << "sum= " << sum << endl;
    return 0;
}
Last edited on
To be fair, my function does have a small bug, but that's for the OP (or his instructor) to find and fix.
closed account (o3hC5Di1)
Does it have something to do with pow and datatypes?

(No trying to spoil things here, genuinly interested, yes or no will do :) )

Thanks,
NwN
Well there's a logical flaw in there.

Correct version is here (since I guess OP's long gone anyway): http://ideone.com/7B9Sk
closed account (o3hC5Di1)
Ah I see now - thanks a lot!

N
Last edited on
Topic archived. No new replies allowed.