Java

Copy Code

int calc(int number) { if (number == 1) return number; int value = number; for (int i = number; i > 1; --i) { value += (int)Math.pow(10, i - 1) * number; } return value + calc(number - 1); }

See more:

Copy Code

a Java program to print the sum of the series 1-22+333-4444+ … upto n terms (without using string functions) Sample Input I: 4 (number of terms) Sample Output I: -4132 Sample Input II: 3 (number of terms) Sample Output II: 312

Copy Code

import java.util.*; class solution { static int calculateSum(int n) { // Returning the final sum //error return ((int)Math.pow(10, n + 1) * (9 * n + 1) + 10) / (int)Math.pow(9, 3) - n * (n - 1) / 18; } // Driver code public static void main(String ar[]) { // no. of terms to find the sum int n=3; System.out.println("Sum= "+ calculateSum(n)); } }

Comments

This will work, but you need to be able to explain it as part of your assignment. You could start by adding some print/debug statements to show what happens at each stage.

Java

Copy Code

int calc(int number) { if (number == 1) return number; int value = number; for (int i = number; i > 1; --i) { value += (int)Math.pow(10, i - 1) * number; } return value + calc(number - 1); }

Comments

Oh, recursion!

5.

5.

Yes, and it took me some time ... :)

5ed!

The 'iterative' alternative to *Richard*'s solution:

Java

Copy Code

import java.util.*; class solution { static int calculateSum(int n) { int sum = 1; for (int i=2; i<=n; ++i) { int term = i; for (int j=1; j<i; ++j) { term = (term * 10) + i; } if ( (i % 2) == 0) sum -= term; else sum += term; } return sum; } // Driver code public static void main(String ar[]) { // no. of terms to find the sum int n=4; System.out.println("Sum= "+ calculateSum(n)); } }

Comments

+5. I thought about doing it this way, but needed a challenge.

Do not see your 5, Richard. Mine was first ;)

I guess I missed it. Thanks also for the 5 above.

5ed!

Thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900