Figuring out some sum - java

You are given the sum 1 + (1+3)/2 + (1+3+5)/4 + … + (2.n-1)/ 2^(n-1). You should compile a program that (given integer N) finds and displays the value of the sum to the N-th addend.
I've written some code but I can't figure out the formula... Help?
Here is my code:
Scanner input = new Scanner(System.in);
System.out.print("n = ");
int n = input.nextInt();
double sum = 0;
for(int i = 1; i <= n; i++) {
sum = sum + (2 * i - 1) / (Math.pow(2, i - 1));
}
System.out.println(sum);

According to Pshemo's notice that 1+3+5+...+n = (n-1)^2 then your formula will be
And your code will be
Scanner input = new Scanner(System.in);
System.out.print("n = ");
int n = input.nextInt();
double sum = 0;
for(int i = 1; i <= n; i++) {
sum += 2 * Math.pow(i, 2) / Math.pow(2, i);
}
System.out.println(sum);

Related

Multiple the sum of digit of a number

I am having a hard time figuring out the solution to this problem. I need to write a program that gets an input n (via scanner), then goes with a for loop till that input number, checks if the numbers are divisible by 13 and then multiplies the digits of each number.
So for an example, if the input number is 40, the divisible numbers by 13 would be 13, 26, 39
1+3 = 4,
2+6 = 8,
3+9 = 12
so that's 4*8*12 = 384.
My current code, but I'm stuck here. I probably didn't do it right, too:
Scanner myScanner = new Scanner(System.in);
int num = myScanner.nextInt();
int sum = 0;
for (int i = 0; i < 30; i = i + 1) {
if (i % 13 == 0) {
while (i > 0) {
int add = i % 10;
sum = sum + add;
i = i / 10;
}
}
}
You're computing the sum of the digits, not the product. Also, you're loop is going to 30, not to num. (There's also no reason to start the loop at 0 instead of 1.) Finally, you shouldn't be changing i inside the loop itself; that will screw up the iteration logic. Use an auxiliary variable. Something like this (untested) should work:
Scanner myScanner = new Scanner(System.in);
int num = myScanner.nextInt();
int prod = 1;
for (int i = 1; i < num; i++) {
if (i % 13 == 0) {
int j = i,
sumOfDigits = 0;
while (j > 0) {
int digit = j % 10;
sumOfDigits += digit;
j /= 10;
}
prod *= sumOfDigits;
}
}
Your whole code is messy. You need to work more on loops and variable assignments and scopes.
Given below is the correct code.
Scanner myScanner = new Scanner(System.in);
int num = myScanner.nextInt();
int mul = 1;
for (int i = 1; i < num; i = i + 1) {
if (i % 13 == 0) {
int sum = 0;
int number = i; // = some int
while (number > 0) {
sum = sum + (number % 10);
number = number / 10;
}
mul = mul * sum;
}
}
System.out.println(mul);
myScanner.close();
Another way to do it, change the number that are divisible to char array, then add and multiply.
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number: ");
int num = sc.nextInt();
int prod = 1;
for (int i = 1; i < num; i++) {
if (i % 13 == 0) {
String number = String.valueOf(i);
char[] digits1 = number.toCharArray();
int sum = 0;
for (char ii:digits1) {
sum = Character.getNumericValue(ii) + sum;
}
prod = prod*sum;
}
}
System.out.println(prod);

how to exclude negative numbers from average calculation in while loop

I have a program that accepts user inputs and calculate Max, Min, and Average. The program closes when the user inputs any negative number. How do i exclude the negative number from the average calculation? Here is what i have so far.
// variable
double n = 1;
double ave = 0;
double sum = 0;
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE ;
int count = 0;
double neg;
//creat scanner object
Scanner input = new Scanner(System.in);
//loop
while (n > 0) {
System.out.print("Input an income (any negative number to quit): ");
n = input.nextDouble();
sum = sum + n;
count++;
ave = sum / count;
if(n<0) neg = n;
if(n>max && n >= 0 ) max = n;
if(n<min && n >= 0) min = n;
if(n>0) ave = n; }
System.out.print(" Average " + ave + "\n Maximum " + max + "\n Minimum " + min);
}
}
Add an if condition:
n = input.nextDouble();
if(n < 0)
break;
sum = sum + n;
The following code only sums the input numbers when n is not negative.
import java.util.Scanner;
public class sample {
public static void main(String[] args) {
double n = 1;
double ave = 0;
double sum = 0;
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE;
int count = 0;
double neg;
Scanner input = new Scanner(System.in);
// loop
while (n > 0) {
System.out.print("Input an income (any negative number to quit): ");
n = input.nextDouble();
if(n >= 0){
sum = sum + n;
count++;
}
if (n < 0)
neg = n;
if (n > max && n >= 0)
max = n;
if (n < min && n >= 0)
min = n;
if (n > 0)
ave = n;
}
System.out.print(" Average " + ave + "\n Maximum " + max
+ "\n Minimum " + min);
}
}
Try this:
double n = 1;
double ave = 0;
double sum = 0;
double max = Double.MIN_VALUE;
double min = Double.MAX_VALUE ;
int count = 0;
// create scanner object
Scanner input = new Scanner(System.in);
// loop until n is negative
while (n >= 0) {
System.out.print("Input an income (any negative number to quit): ");
n = input.nextDouble();
if (n >= 0) {
if (n > max) max = n;
if (n < min) min = n;
sum = sum + n;
count++;
}
}
if (count > 0)
ave = sum / (double) count;
System.out.print(" Average " + ave + "\n Maximum " + max + "\n Minimum " + min);

How do I add power in java?

I am new to Java and stackoverflow. I am writing a program that can add power in Java, for example: 2^1, 2^1+2^2, 2^1+2^2+2^3,.. so on.
I have written below program and I don't know what I am doing wrong when I am trying to add the powers. I just get 2^1 2^2 2^3,... as output. I hope you get the idea from my code and it will be a great help if you guys can help me learn.
Thank you in advance!
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a: ");
int a = sc.nextInt(); //a = first number
System.out.print("Enter b: ");
int b = sc.nextInt(); //b = second number
System.out.print("Enter t: ");
int t = sc.nextInt(); //t = no. of iterations
int x=0, sum = 0;
for (int i = 0; i < t;) {
for (int j = 0; j < t; j++) {
int pow = (int) Math.pow(2, i);
x = a + (pow * b);
i++;
System.out.printf("%d ", x);
sum = x;
}
sum = x + sum;
System.out.println(sum);
}
}
According to Mathematics rules, if it is addition among the numbers, for example 2^1 + 2^2 + 2^3 + 2^4... Then it is simple you don't need two loops and the t variable. You just need the base and the last exponent limit.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the base: ");
int a = sc.nextInt(); //a = first number
System.out.print("Enter iterations: ");
int b = sc.nextInt(); //b = No of iterations
int sum = 0;
for (int i = 1; i <= b; i++) {
sum += Math.pow(a, i);
}
System.out.println("The sum is " + sum);
}
But if there is multiplication among the numbers, then you will add the exponents if the base is same. Fox example 2^1 * 2^2 * 2^3 * 2^4.... Then you may do it as below.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the base: ");
int a = sc.nextInt(); //a = first number
System.out.print("Enter iterations: ");
int b = sc.nextInt(); //b = No of iterations
Double res;
int powerSum = 0;
for (int i = 1; i <= b; i++) {
powerSum += i;
}
System.out.println("Power sum is " + powerSum);
res = Math.pow(a, powerSum);
System.out.println("The result is " + res);
}
In your inner loop
int pow = (int) Math.pow(2, i);
shouldn't you be using j instead of i?
Very simply you can do it as below:
public static int getPow(int num, int pow) {
if (pow < 2) {
return num;
}
return (int) Math.pow(num, pow) + getPow(num, --pow);
}
Usage:
int pow = getPow(2, 4);// 2*1 + 2*2 + 2*2*2 + 2*2*2*2 = 2+4+8+16 = 30
System.out.println("pow = " + pow);
And Result:
pow = 30

How to display individual digits of integer input?

I am working on an assignment which prompts the user to input an integer, and displays that integer with the digits separated by spaces, and provides the sum of those digits. I have this working, but my individual digit display is form the last digit to the first. How can I make it display the digits from first to last?
Here is what I have so far:
import java.util.*;
public class SeparateAndSum{
static Scanner console = new Scanner(System.in);
public static void main(String[] args)
{
int num, temp, sum;
System.out.print("Enter a positive interger: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
do
{
temp = num % 10;
sum = sum + num % 10;
num = num / 10;
System.out.print(" " + temp + " ");
}while (num > 0);
System.out.println("The sum of the digits = " + sum);
}
}
One option would be to use the String#valueOf(Integer) method.
Example
int input = 12345;
String inputStr = String.valueOf(input);
for(char c : inputStr.toCharArray()) {
// Print out each letter.
}
if you use the method String.valueOf(12345)
you can easily reverse the String with the method in this library:
https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringUtils.html#reverse(java.lang.String)
StringUtils.reverse(String.valueOf(input));
Here is the solution
import java.util.*;
public class SeparateAndSum{
static Scanner console = new Scanner(System.in);
int num, temp, sum;
System.out.print("Enter a positive interger: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
ArrayList<Integer> values = new ArrayList<>();
do
{
temp = num % 10;
sum = sum + num % 10;
num = num / 10;
values.add(temp);
}while (num > 0);
Collections.reverse(values);
Iterator<Integer> it = values.iterator();
while(it.hasNext()){
System.out.println(" "+it.next()+" ");
}
System.out.println("The sum of the digits = " + sum);
}
}
BTW you should have to import ArrayList etc.
I would highly recommend putting the number into a String and then reading it, parsing it, and use the number however you want. As follows,
int input = 12345;
String inputString = input + "";
int sum = 0;
for (int i = 0; i < inputString.length(); i++) {
sum += Integer.parseInt(inputString.charAt(i) + "");
}
System.out.println(sum);
However an alternative way, not as pretty is..
int input = 12345;
int sum = 0;
while (input > 0) {
int i = (input + "").length() - 1;
int n = (int) (input / Math.pow(10, i));
input -= (int) (n * Math.pow(10, i));
sum += n;
}
System.out.println(sum);

How to sum array contents with their powers of 3

I need to do something like this - user types in a number (e.g. 5) and the program shows the result of the following action: 1*1*1 + 2*2*2 + 3*3*3 + 4*4*4 + 5*5*5.
My code is following:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter your number:");
int n = input.nextInt();
int a[] = new int[n];
int power = 0;
int sum = 0;
for (int i = 1; i <= a.length; i++)
{
power = (int) pow(i, 3);
// Maybe here'a the problem, a[n] has not enough space for the power (???)
sum += a[power];
}
System.out.println(Result: " + sum);
}
I think that I understand why this code doesn't work but I will appreciate any ideas about how to do it properly and runnable.
sum += power;, no need for a.
Or simply use math :
int n = input.nextInt();
int result = (int)(0.25 * Math.pow(n, 2)*Math.pow(1+n,2));
Or even more simple, as #ajb said :
int result = n*n*(n+1)*(n+1)/4;
Change:
sum += a[power];
to
a[i-1] = power;
sum += a[i-1];
or forget the array altogether
sum += power;
sum += a[power]; doesn't exist.
You need to :
store the power value in the ith array item.
add the ith array value to the sum
Change your loop body to:
power = (int) pow(i, 3);
a[i - 1] = power;
sum += a[i - 1];
You're doing way too much work.
Scanner input = new Scanner(System.in);
System.out.println("Enter your number:");
int n = input.nextInt(),
sum = 1;
for (int i=2; i<=n; i++) {
sum += (int) Math.pow(i,3);
}
done. sum now contains the sum 1³ + 2³ + 3³ + ...
Or, more efficiently with exactly the same functionality:
Scanner input = new Scanner(System.in);
System.out.println("Enter your number:");
int n = input.nextInt(),
sum = 1;
while(n > 1) {
sum += (int) Math.pow(n--,3);
}
Why? Because 1 + 5³ + 4³ + 3³ + 2³ is the same as 1³ + 2³ + 3³ + 4³ + 5³
Of course you could also just directly compute that value, using actual maths, cutting all the entire algorithm with a simple arithmetic oneliner.

Categories