Trying to add a sum of first consecutive odd squares? - java

I'm trying to add a sum of consecutive odd squares to add up to the same number. For example: the first 4 consecutive odd square numbers added together will equal 84, (1*1) + (3*3) + (5*5) + (7*7) = 84. The Attached is my code. Result 2, the non-loop code, is correct. I need help on resolving what I'm doing wrong with result1's loop code.
Inputnumber equals the number of odd squares requested.
public static int sumWithLoop (int inputNumber)
{
int result1 = 0;
int counter = 1;
while (counter <= inputNumber)
{
result1 = result1*result1 + counter;
counter = counter + 2;
}
return result1;
}
public static int sumWithoutLoop (int inputNumber)
{
int result2 = (inputNumber*(2 * inputNumber - 1) * (2 * inputNumber + 1) / 3);
return result2;
}

You probably meant result1 = result1 + counter * counter; instead of result1 = result1*result1 + counter;.

Most of your problem is in the math inside the while loop.
result1 should be initialized to 1. (At least the way I'm doing it.)
Your first line in the block squares result1 and adds counter to it. What you need is something more like this:
result1 = result1 + (int) (Math.pow(1 + 2 * counter, 2));
This takes result1 and adds the next odd square to it. (1 + 2 * counter = the next odd number)
With the above code to determine the next odd number, counter should be incremented by 1 at the end of the while loop, rather than 2 (because I multiply counter by 2 in the Math.pow function).
My final code looks like this:
public static int sumWithLoop (int inputNumber)
{
int result1 = 1;
int counter = 1;
while (counter < inputNumber)
{
result1 = result1 + (int) (Math.pow(1 + 2 * counter, 2));
counter = counter + 1;
}
return result1;
}
It returns 84 when inputNumber is 4, 165 when it's 5, 286 when it's 6, etc., so it looks like it works.
Hope this helped!
P.S. Just FYI, I/you could have used result1 += (int) (Math.pow(1 + 2 * counter, 2)); in the first line in the while loop. The difference is the += operator, which adds the following value to the preceding variable. It's more concise than this = this + somethingMore;
Also, in the second line, we could've used counter++;, instead of counter = counter + 1; ++ adds one to the variable it's used on.

Related

Calculating how many times a number is added to itself until it reaches an arbitrary value?

Considering two variables:
"n" is any arbitrary value.
"i" is the number of times a value is increased in a sum before it reaches the value of "n".
So for instance if the value n = 344 is chosen, then i = 26 because:
26 + 25 + 24 + ... + 3 + 2 + 1 = 351
26 is how many times the variable "i" gets added together in a descending order before it either is equal to n = 344 or the first time it surpasses.
public class Trstuff{
public static void main (String [] arg) {
int n = 4;
int i = computeIndex(n);
System.out.print(i);
}
public static int computeIndex(int n) {
int i = 1;
int sum = 0;
for(i = 1; sum <= n; i++) {
sum = sum + i;
}
return i;
}
}
My goal is to choose any "n" value and then have the program return the variable "i" to me.
As my program stands, I thought it should be correct, but somehow it's not. Here is the example with n = 4.
The result should be that "i = 3" because:
1 + 2 = 3
1 + 2 + 3 = 6
So the ascending value of "i" in the loop is added 3 times before the loop supposedly should stop because of the expression "sum <= n" in the loop.
However, when I run the program it returns the value 4 instead. I simply cannot figure out what is wrong and why my program gives me 4 instead of the correct answer, 3?
Read the for loop as follows:
for every value of i while sum smaller or equal to n, add i to sum and increment i
The last part of the line and increment i is executed after the sum of sum + i, but before the next check which checks if sum is smaller or equal to n, with as result that i always is one larger than expected.
The solution could be to use a different exit (different solutions exist):
public static int computeIndex(int n) {
int i = 1;
int sum = 0;
while true {
sum = sum + i;
if sum<n {
i++;
} else break;
}
return i;
}
the sum of p consecutive integers starting at 1 is p*(p+1)/2
so basically you need to solve x^2+x-2*n = 0, with solution
x = 0.5*(sqrt(1+8n)-1)

Trying to calculate a factorial e^x, x being what the user enters, having trouble with the formula

I am in a Java class and it's still early in the class. The assignment is to:
e^x Approximations
The value ex can be approximated by the following sum:
1 + x + x^2/2! + x^3/3! + …+ x^n/n!
The expression n! is called the factorial of n and is defined as: n! = 1*2*3* …*n.
Write a program that takes a value of x as input and outputs four approximations of ex done using four different values of n: 5, 10, 50, and 100. Output the value of x the user entered and the set of all four approximations into the screen.
Sample formula use: calculating e^7 using approximation with n = 5
1 + 7 + 7^2/2! + 7^3/3! + 7^4/4! + 7^5/5!
I've got all the rest to work, including getting n to be 5, 10, 50 and 100. I thought I had the factorial formula figured out and I used the number 4 like the sample we were show and my numbers done match. Could really use another set of eyes.
Here's my code with forumla (x is the value the user enters and n is the 5, 10, 50 and 100):
/**
* myFact takes in x and calculates the factorial
* #param x
* #param n
* #return the factorial as a long
*/
public static long myFact(int x, int n) {
//declare variables
long sum = x;
for (int i=2; i <= n; i++) {
sum += ((Math.pow(x, i))/i);
}
return (sum + 1);
}
}
Here's the main class where I am calling the function. The error I suppose could be there too:
public static void main(String[] args) {
//declare variable for user input and call method to initialize it
int x = getNumber();
long fact;
int n;
//Output first line
System.out.println("N\t approximate e^" + x);
for (n = 5; n <= 100; n *= 2) {
if (n == 10) {
fact = myFact(x, n);
System.out.println(n + "\t " + fact);
n += 15;
} else {
fact = myFact(x, n);
System.out.println(n + "\t " + fact);
}
}
}
Thanks for taking a look at this, it's taken me hours to get this as the teacher gave us very little help.
You did a mistake in
sum += ((Math.pow(x, i))/i);
here you need to calculate the i!. Add below method in your code
public static int fact(int i){
int fact = 1;
for (int n = i; n > 0; n--) {
fact = fact * n;
}
return fact;
}
Also change sum += ((Math.pow(x, i))/i) to
sum += ((Math.pow(x, i))/fact(i));

Doing a factorial with only one while loop

I'm trying to find the factorial of 9 down to 0, only using one while loop, but my idea isn't outputting a value.
I figured out the way to do it using two while loops:
int i;
count = 9;
while (count >= 0){
value = count;
i = count-1;
while (i > 0){
value = value * i;
i--;
}
System.out.print(value + ", ");
}
This worked but I've tried to change it to use only one while loop and got this:
int i;
for (count = 9; count < 0; count--){
value = count;
i = count-1;
while (i > 0){
value = value * i;
i--;
}
System.out.print(value + ", ");
}
I'm not completely sure if I'm using the for statement correctly but I think I am, or at least I think it should output something so I can debug it.
Could someone give me a hint in the right direction?
This will give you all the factorials from 9 down to 1 :
int i=1;
int value=1;
String res = "";
while (i <= 9){
value = value * i;
res = value + ((i>1)?",":"") + res;
i++;
}
System.out.print(res);
Output :
362880,40320,5040,720,120,24,6,2,1
Perhaps it's cheating, since I'm calculating the factorials in ascending order from 1! to 9!, but I'm reversing the order of the output in order to get the required result.
Edit :
If you also want 0! to be printed, a small change can do the trick :
int i=1;
int value=1;
String res = "";
while (i <= 10){
res = value + ((i>1)?",":"") + res;
value = value * i;
i++;
}
System.out.print(res);
Output :
362880,40320,5040,720,120,24,6,2,1,1
First, the reason why your second loop doesn't work is that you have the wrong condition in the for. The condition in the middle is one that will cause the loop to continue, not to stop. So what you were saying was "start from 9, and work while the number is less than 0". But of course, your number is greater than zero to begin with.
Second, I believe using a for loop is a little bit of cheating, because a for loop is just a specific case of while loop.
Now to the problem of the factorial itself. You know that a factorial n! is defined as (n-1)!*n.
The basic loop for calculating one specific factorial is:
int n = 5;
int factorial = 1;
while ( n > 0 ) {
factorial *= n;
n--;
}
System.out.println( "Factorial is: " + factorial );
This will give you the factorial of five. But it's not exactly based on the formula we are talking about. There is another way to calculate it, starting from 1:
int n = 5;
int factorial = 1;
int count = 1;
while ( count <= n ) {
factorial *= count;
count++;
}
System.out.println( "Factorial is " + factorial );
The interesting part about this way of doing it is that in every stage of the loop, factorial is actually the value (count-1)! and we are multiplying it by count. This is exactly the formula we were talking about.
And the good thing about it is that just before you did it, you had the value of the previous factorial. So if you printed it then, there you'd get a list of all the factorials along the way. So here is a modified loop that prints all the factorials.
int n = 9;
int factorial = 1;
int count = 0;
while ( count < n ) {
System.out.println( "Factorial of " + count + " is " + factorial );
count++;
factorial *= count;
}
System.out.println( "Factorial of " + n + " is " + factorial );
Note that I modified it a little more so that it will work with zero. The factorial of zero is a special case so we shouldn't multiply by zero - that will make all the factorials wrong. So I changed the loop to multiply only after I increase count to 1. But this also means that you have to print the final factorial out of the loop.
Just first assign value=i, then run your loop. You can get the factorial with only while loop.
Important: Because n!=n*(n-1)!, therefore, i-- should must be perform before value = value * i.
public static void main(String args[]) {
int value=5;
int i=value;
while (i > 1){
i--;
value = value * i;
}
System.out.print(value);
}
Update: If you want to count factorial of 0 to 9, then use this code: (It includes factorial of 0 also)
public static void main(String args[]){
int countLowest=0;
int countHighest=9;
int value=1;
while (countLowest<= countHighest){
if(countLowest==0)
value = value * (countLowest+1);
else
value=value*countLowest;
countLowest++;
System.out.println("Factorial of "+(countLowest-1)+" is "+value);
}
}
Result:
Factorial of 0 is 1
Factorial of 1 is 1
Factorial of 2 is 2
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
Factorial of 6 is 720
Factorial of 7 is 5040
Factorial of 8 is 40320
Factorial of 9 is 362880
count = 9;
sum=1;
while (count >= 1){
sum*=count;
--count;
}
System.out.print(sum);
it will give you 9!=362880

Array index out of bounds: 30 (Java)

I am writing a program to print out a user inputed integer into binary form.
When I run it and input, say the number 5, it crashes and gives me the error:
java.lang.ArrayIndexOutOfBoundsException: 30
at PrintBinaryDigitsFixed.main(PrintBinaryDigitsFixed.java:27)
i.e the line "digits[counter] = number % 2;"
Why am I getting an out of bounds exception? It should assign the remainder to the first element then move on to the second shouldn't it?
I feel like I'm making a glaringly obvious mistake but I can't tell what it is
final int MIN = 0;
final int MAX = (int) (Math.pow(2, 30) - 1);
int[] digits = new int[30]; //array to hold the digits
int number = readInput
("Enter an integer from " + MIN + " to " + MAX, MIN, MAX);
int counter = 0;
int modNumber = 2;
while(modNumber / 2 != 0)
{
digits[counter] = number % 2;
modNumber = number / 2;
counter++;
}
System.out.print(number + " in binary form is ");
listBackwardsFrom(digits, counter);
Thanks
You never change number in your loop, and you assign modNumber = number / 2 in the loop, so from the second iteration onward modNumber is a constant (for most of the first iteration it's 2, but then you assign number / 2 to it); if you reach that point at all, you'll stay there. So the loop continues until counter reaches 30, at which point digits[counter] throws the exception.

Loop to Find Sum of Digits

I am trying to write a simple and quite useless program to generate a list of all integers 1><1000 where the sum of digits is 11. Every time I run this, I end up in an infinite loop. I've tried different things - for(){}, while(){}, adding a if(count>500){break;} to halt it after the loop counter reaches 500....still nothing...where am I going wrong in this?
Thanks in advance
//loops through all numbers whose sum of digits is 11
for(int number = 29; number < 1000; number++) {
//checks the values of the 100,10,and 1 position
int hPlace = number / 100; number = number - (hPlace * 100);
int tPlace = number / 10; number = number - (tPlace * 10);
int oPlace = number;
//sum of digits
int i = hPlace + tPlace + oPlace;
//prints if sum of digits is 11
int count = 0;
if (i == 11) {
count++;
System.out.print(i + " ");
}
//new line after every 10 numbers -- just for formatting
if (count % 10 == 0) {
System.out.println("");
}
}
You are using same variable as controller for your fors. Try to change the controller variable within the for structure from number to number1
You are changing the variable here:
---------------------------------
int hPlace = number / 100; number = number - (hPlace * 100);
---------------------------------
Don't do this
number = number - (hPlace * 100);
when your condition is dependent on number
for(int number = 29; number < 1000; number++)
because you have two nested for loops which both of them use the same variable as counter
for(int number = 29; number < 1000; number++) {
for(number = 29;number < 930;number++) {
//loops through all numbers whose sum of digits is 11
for(int number = 29; number < 1000; number++) {
//checks the values of the 100,10,and 1 position
int hPlace = number / 100;
**number** = number - (hPlace * 100); // PROBLEM!!!
int tPlace = number / 10;
**number** = number - (tPlace * 10); // PROBLEM!!!
int oPlace = number;
//sum of digits
int i = hPlace + tPlace + oPlace;
//prints if sum of digits is 11
int count = 0;
if (i == 11) {
count++;
System.out.print(i + " ");
}
//new line after every 10 numbers -- just for formatting
if (count % 10 == 0) {
System.out.println("");
}
}
if(count>500){break;} to halt it after the loop counter reaches 500....still nothing
This won't work because you're redeclaring count with an initial value of 0 everytime. So the if will always return false.
Also, these following lines:
int hPlace = number / 100; number = number - (hPlace * 100);
int tPlace = number / 10; number = number - (tPlace * 10);
Modify number, which is your loop variable. Your loop will not perform correctly if you modify the loop variable in unexpected ways. Instead, copy the value over to another variable.
Don't change the value of you loop control variable inside the loop, or dangerous things may result. Instead, copy the value into a new variable and use that in the loop.
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class SumDigits
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a Number:");
String string=br.readLine();
System.out.println("length of Number:"+string.length());
int sum=0;
int number=0;
for(int i=0;i<=string.length()-1;++i)
{
char character=string.charAt(i);
number=Character.getNumericValue(character);
sum=sum+number;
}//for
System.out.println("Sum of digits of Entered Number:"+sum);
}//main()
}//class

Categories

Resources