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.
Related
How can I apply string.format and printf to my output so that I can align it as per my assignment requirement?
I have 3 inputs to my method, 2 of which are char arrays which hold the two numbers, and an int array which holds their sum.
I have formatted the numbers and sum so that it is a string with appropriate commas interspersed. My task is to now align these outputs so that they always align themselves properly. The problem is I can't just set the column width to a specific number seeing as the inputs vary due to user input.
Ex: User inputs number1 and number2 (up to a max value of 30 digits), the program sums up the numbers and returns the total.
This is my code and current output:
import java.util.Scanner;
import java.util.Arrays;
public class Lab8{
public static void main(String[] args){
char[] num1 = {'9','2','3','8','7','4','8','6','7','2','9'};
char[] num2 = {'3','9','9','8','3','9','2','8','3','4','9','4','5','8'};
//getNumber("First Number: ");
//getNumber("Second Number: ");
//printArray(num1);
//System.out.println();
//printArray(num2);
int[] finalTotal = sumArrays(num1,num2);
//sumArrays(num1, num2);
printOutput(num1, num2, finalTotal);
}
//--------
/** Read a line of message from keyboard and return it as an array of char
#return: Array of characters
*/
public static char[] getNumber(String msg){
String myMessage;
System.out.print(msg);
Scanner input = new Scanner(System.in);
myMessage = input.nextLine();// Read a line of message
return myMessage.toCharArray();
}
public static int[] sumArrays(char[] num1, char[] num2){
int sum= 0, carry = 0, size = 0, min = 0;
if(num1.length > num2.length){
size = num1.length + 1;
min = num2.length;
}else{
size = num2.length + 1;
min = num1.length;
}
int[] sumArray = new int[size];
int i = num1.length-1;
int j = num2.length-1;
int k = size-1;
while(i >= 0 && j >=0){
sum = Character.getNumericValue(num1[i]) + Character.getNumericValue(num2[j]) + carry;
i--;
j--;
sumArray[k] = sum % 10;
sum = sum / 10;
carry = sum % 10;
k--;
}
while(i >= 0){
sum = Character.getNumericValue(num1[i]) + carry;
sumArray[k] = sum % 10;
sum = sum / 10;
carry = sum % 10;
i--;
k--;
}
while( j >= 0){
sum = Character.getNumericValue(num2[j]) + carry;
sumArray[k] = sum % 10;
sum = sum / 10;
carry = sum % 10;
j--;
k--;
}
sumArray[k] = carry;
int[] finalSum = new int[sumArray.length-1];
finalSum = printArray(sumArray);
return finalSum;
}
public static void printOutput(char[] num1, char[] num2, int[] sum){
char[] largest = new char[1];
char[] smallest = new char[1];
char[] tmp = new char[1];
if(num2.length > num1.length){
largest = num2;
smallest = num1;
}else{
largest = num1;
smallest = num2;
}
String number1 = formatString(largest);
String number2 = formatString(smallest);
String total = formatString(sum);
System.out.printf("%s%n", number1 + " +");
for(int i = 0; i < (number1.length() - number2.length()); i++){
System.out.print(" ");
}
System.out.printf("%s%n%s%n%s", number2, totalLine(sum),total);
}
public static String formatString(char[] num){
String formattedString = "";
for(int i = 0; i < num.length; i++){
if(i == 0){
formattedString = num[num.length-1-i] + formattedString;
continue;
}
if(i % 3 == 0){
formattedString = "," + formattedString;
}
formattedString = num[num.length-1-i] + formattedString;
}
return formattedString;
}
public static String totalLine(int[] num){
String totalLine = "";
for(int i = 0; i < num.length; i++){
totalLine = "- " + totalLine;
}
return totalLine;
}
public static String formatString(int[] num){
String formattedString = "";
for(int i = 0; i < num.length; i++){
if(i == 0){
formattedString = num[num.length-1-i] + formattedString;
continue;
}
if(i % 3 == 0){
formattedString = "," + formattedString;
}
formattedString = num[num.length-1-i] + formattedString;
}
return formattedString;
}
public static int[] printArray(int[] arr){
int[] sum = new int[arr.length-1];
if(arr[0] == 0){
for(int i = 1; i < arr.length; i++){
sum[i-1] = arr[i];
}
}else{
for(int i = 0; i < arr.length; i++){
sum[i] = arr[i];
}
}
return sum;
}
}
OUTPUT(wrong)
39,983,928,349,458 +
92,387,486,729
- - - - - - - - - - - - - -
40,076,315,836,187
OUTPUT(correct way)
39,983,928,349,458 +
92,387,486,729
--------------------
40,076,315,836,187
As you can see, my formatting is flawed. I'm totally unsure how to properly format this output so that it displays correctly every time even with differing number values. It should be formatted with the larger number above the smaller number and then a total line followed by the sum.
So after reading some more I realized what I was trying to achieve didn't necessarily require string formatting or printf statements. I ended up, like the previous comments and answer above suggested, just formatting the output with multiple print statements. It's definitely not the most beautiful code to look at but it gives me the exact output I was after.
This was the code that did the trick:
System.out.println(" " + number1 + " +");
for(int i = 0; i < (number1.length() - number2.length()); i++){
System.out.print(" ");
}
System.out.println(" " + number2);
System.out.print(" ");
for(int j = 0; j < ((number1.length() - number2.length())+ number2.length()+1); j++){
System.out.print("-");
}
System.out.println();
System.out.print(" " + total);
Based on your comments, it seems like the math is tripping you up. Let me see if I can help.
(You implied this was homework, so I'm not going to literally give you the code, but this should set you on the right path. I'm sure you can implement it yourself.)
The number of digits in a number is:
Math.floor(Math.log10(x)) + 1
(See this conversation for a proof.)
Use that to find the length of the answer. (This is always going to be the longest number or tied for the longest, since you're adding numbers together.) Make your line of ---s this long.
Append to the front of each line length of that line - length of the answer number of spaces.
(If you want to have a certain number of spaces as an indent on the whole problem, as you have in your example, then append length of line - length of answer + indent number of spaces to the front of each line instead.)
Append + (space and a plus) to the end of the first line, and (two spaces) to the other lines.
That should work!
You can use ArrayLists instead of char arrays to simplify math. But you have to adjust the code a bit. Here is the procedure.
Get two lines of inputs in to two array lists using getNumber() method. (let's call the B and C)
Take the sum to a third array list using the sum method.(Let's call A)
Find the sizes of array lists using size() method in arraylist.
Compare the sizes and get the difference between biggest array list and other two array lists seperately.(Largest would be A so get A-B and A-C). And store sizes B and C sizes for future use in two variables.
Add (A-B) number of whitespaces(" ") into B arraylist staring from 0 index using add(index,object) method in array list.(in add(index,object) method shifts the element currently at that position (if any) and any subsequent elements to the right)
Do the Same for the C array list as well as well.
Find the Array List highest value from B and C using the previously stored sizes and append that array list in to the formatted string first.(using a loop)
Then after "+" and "\n", append the second array list to the format string.
Finally append the array list containing sum(A) into the format string.
As we added whitespaces to make all arrays the same size, the formatted string should be well formated.
Given a pattern... (1 / 2)^2 + (2 / 3)^2 + (3 / 4)^2 + ...
Input is n; which becomes the highest denominator used in the summation of these fractions.
When a user enters n = 2; the sum is simply (1 / 2)^2.
When a user enters n = 3; the sum is (1 / 2)^2 + (2 / 3)^2
I believe I've solved this problem (we assume the user enters an integer greater than or equal to 2)...
int n;
double sum = 0, counter = 2;
n = console.nextInt();
while(counter <= n) {
sum = sum + Math.pow(--counter/++counter, 2);
counter++;
}
System.out.println("Sum is " + sum);
Is there any "obvious" way to simplify my solution to this problem (whilst remaining as a while-loop)? This is one of the first loops I've ever written. I'm not sure if less variables can be used to solve this problem.
Try
int n;
double sum = 0, counter=1;
n = console.nextInt();
while((counter+1) <= n) {
sum = sum + Math.pow(counter/(counter+1), 2);
counter++;
}
System.out.println("Sum is " + sum);
Why dont simplify it and write this:
int n;
double sum = 0, counter = 2;
n = console.nextInt();
while(counter <= n) {
sum = sum + Math.pow((counter - 1)/counter, 2);
counter++;
}
System.out.println("Sum is " + sum);
i dont know who is computed first (++counter) or (--counter), if (--counter) your response is correct, but dont pollute your code with ++ or --, use them only if you need it.
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);
The sequence is: sum = 1 + 1/2 + 1/4 + 1/9 + 1/16 + 1/25+...
When I enter "2" it just gives me the sum of 1.25. How do you get it so when "2" is entered, it is adding 1 + 1/2?
Oh and I'm in an entry level java course so I we cant use arrays or anything that advance yet.
Thanks in advance!
import java.util.Scanner;
public class Sum
{
public static void main(String[] args)
{
//declarations
Scanner scan = new Scanner(System.in);
double sum = 0;
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
//process
for(int counter = 1; counter <= n; counter += 1)
{
sum += 1.0 / (counter*counter);
}
System.out.println("The sum is: " + sum);
}
}
Since you say that 1/2 must be part of the sequence, so be it. (But that's a bizarre sequence and I strongly suggest that you double check this with your professor.) I'll assume that the remainder of the sequence is defined by 1/i2. Note that with these assumptions, the sequence terminates at 1/(n-1)2 rather than 1/n2.
You'll need special handling for the cases n == 1 and n > 1. One possibility is to initialize sum to 1 if n == 1; initialize it to 1.5 if n > 1; and otherwise initialize it to 0. Then start the loop at counter = 2 and change the loop termination condition to counter < n (instead of <=).
You need to manage "1" and "2" as special cases.
import java.util.Scanner;
public class Sum
{
public static void main(String[] args)
{
//declarations
Scanner scan = new Scanner(System.in);
double sum = 0;
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
//process
for(int counter = 1; counter <= n; counter += 1)
{
if (counter == 1)
sum = 1;
else if (counter == 2 )
sum += 1.0/((counter-1)+(counter-1));
else
sum += 1.0 / ((counter-1)*(counter-1));
}
System.out.println("The sum is: " + sum);
}
}
If that's your sequence then you should really start by setting the sum equal to 1.5 and then rest of it will work. Your sequence should be a geometric sequence 1/n^2 I think it's a mistake.
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
double sum = 1.5;
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
if(n==1)
System.out.println("The sum is: " + 1);
//process
for(int counter = 2; counter <n; counter++) {
double mul = counter*counter;
sum += 1.0/mul ;
}
System.out.println("The sum is: " + sum);
}
Output :
Enter n:
2
The sum is: 1.5
Enter n:
3
The sum is: 1.75
The following code will solve your problem, i have used Math.pow() to get the sequence running and not multiplying it twice.
public static void main(String[] args) throws UnknownHostException {
//declarations
Scanner scan = new Scanner(System.in);
//to generate this sequence we take the first two as constants and start generating from the third onwards
double first = 1;//first number in the sequence
double second = 0.5;//second number in the sequence
double sum = first+second;//adding first and second
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
if(n==1){
System.out.println("The sum is: " + first);
return;
}
if(n==2){
System.out.println("The sum is: " + sum);
return;
}
//process
for(int counter = 2; counter <n; counter += 1)
{
sum += 1.0 / Math.pow(counter, 2);//will be computed when you enter values when n is more than 3
}
System.out.println("The sum is: " + sum);
}
As per your for loop, the sequence generated will be 1 + 1/(2*2) + 1/(3*3)+ ......
So, when you enter 2 => 1+1/(2*2) = 1+0.25=1.25.
Otherwise, your logic is Good. you can implement few exceptions, but as you mentioned that you re new to Java, you ll slowly encounter them.
Happy Learning Java :)
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);