Java: Sum of all the elements from all possible subsets of a set formed by first n natural numbers
Java Basic: Exercise-193 with Solution
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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/basic/java-basic-exercise-193.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics