w3resource

Java: Sum of all the elements from all possible subsets of a set formed by first n natural numbers


Subset Sums of Natural Numbers

Write a Java program that accepts an integer and sums the elements from all possible subsets of a set formed by the first n natural numbers.

Sample Solution:

Java Code:

// Import Scanner class from java.util package for user input
import java.util.Scanner;

// Main class for the solution
public class Solution {

    // Main method to execute the solution
    public static void main(String[] args) {
        // Create a Scanner object for user input
        Scanner in = new Scanner(System.in);

        // Prompt the user to input a positive integer
        System.out.print("Input a positive integer: ");

        // Read the user input as an integer
        int n = in.nextInt();

        // Calculate the sum of subsets using a mathematical formula
        int result = (n * (n + 1) / 2) * (1 << (n - 1));

        // Display the result of the sum of subsets
        System.out.print("Sum of subsets of n is : " + result);
    }
} 

Sample Output:

Input a positive integer:  25
Sum of subsets of n is : 1157627904

Flowchart:

Flowchart: Java exercises: Sum of all the elements from all possible subsets of a set formed by first n natural numbers

For more Practice: Solve these Related Problems:

  • Write a Java program to count the number of subsets of the first n natural numbers that sum to a specified target value.
  • Write a Java program to determine the maximum subset sum of the first n natural numbers that does not exceed a given limit.
  • Write a Java program to generate and list all possible subset sums from the first n natural numbers.
  • Write a Java program to compute the subset sums of the first n natural numbers that are even.

Java Code Editor:

Company:  Bloomberg

Contribute your code and comments through Disqus.

Previous: Write a Java program to rearrange the alphabets in the order followed by the sum of digits in a given string containing uppercase alphabets and integer digits (from 0 to 9).
Next: Write a Java program to find the all positions of a given number in a given matrix. If the number not found print ("Number not found!").

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.