Click here to Skip to main content
15,077,054 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
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


What I have tried:

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));
 
}
}
Posted
Updated 25-Sep-21 5:07am
Comments
Richard MacCutchan 25-Sep-21 7:13am
   
This is your second such post, and again you have not explained what the problem is. I suggest you work on one problem at a time.

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
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
CPallini 25-Sep-21 10:57am
   
Oh, recursion!
5.
Richard MacCutchan 25-Sep-21 11:30am
   
Yes, and it took me some time ... :)
Maciej Los 26-Sep-21 15:42pm
   
5ed!
The 'iterative' alternative to Richard's solution:
Java
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
Richard MacCutchan 25-Sep-21 11:30am
   
+5. I thought about doing it this way, but needed a challenge.
Maciej Los 26-Sep-21 15:42pm
   
Do not see your 5, Richard. Mine was first ;)
Richard MacCutchan 27-Sep-21 3:43am
   
I guess I missed it. Thanks also for the 5 above.
Maciej Los 26-Sep-21 15:42pm
   
5ed!
CPallini 27-Sep-21 2:03am
   
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