public class Task {
public static void main(String args[]) {
int x = 0, p = 0, sum = 0;
p = 1;
x = 2;
double q;
sum = 0;
while (p < 12) {
q = x + p - (sum + 5 / 3) / 3.0 % 2;
sum = sum + (x++) + (int) q;
System.out.println(sum);
if (x > 5)
p += 4 / 2;
else
p += 3 % 1;
}
sum = sum + p;
System.out.println(sum);
}
}
While proceeding to line 12 (sum = sum + (x++) + (int)q;) i thought sum should be 5 but actually the output is 4. I tried line 12 in the interactions pane and indeed saw that sum=4. I don't get it. Shouldn't x++ yield 3 (x=2) and if this gets added to (int) q ( double q gave me sth like 2.666666), i should be getting 5. Can someone explain to me what happened?
Additionally,after getting my first output, how should I proceed?
The next condition is:
if (x > 5)
p += 4 / 2;
else
p += 3 % 1;
since x<5, i should go for the else condition, right?
My last question is that, after using p += 3%1, my p still remains 1, so do i return back to this loop (since p<12) or do I get out of this loop and proceed to line19? I'm not sure what to do.
In line 12 you are using post increment (x++). You should use pre increment ++x.
Post increment puts the current value of x in your statement, then increases x.
Pre increment initially increases x and after that puts result into your statement.
At your first time, 3%1=0
p +=3%1 => p+=0 thats why p still remains 1
Related
This question already has answers here:
Int division: Why is the result of 1/3 == 0?
(19 answers)
Closed 4 years ago.
I want to solve this math question in processing:
S=1+1/2-1/3+1/4...+1/99-1/100.
Here is my code (don't know why it doesn't work. I suppose it will print one number in the console, but it comes out a series of natural numbers):
float N = 0;
float T = 0;
int i = 1;
void draw() {
for (i = 1; i < 100; i += 2) {
N = N + 1 / i;
T = T + 1 / (i + 1);
}
println(N - T);
}
First off, draw() runs every frame. Use setup() instead, it runs once.
Second, dividing ints results in an int. Go ahead, do println(1/i) and see the magic.
Third, always google around for some time before going to SO. You'll learn more by finding it out yourself. And this was very solvable with google and a little effort ;)
working code:
float N = 0;
float T = 0;
int i = 1;
void setup() {
for (i = 1; i < 100; i += 2) {
N = N + 1.0 / i;
T = T + 1.0 / (i + 1);
}
println(N - T);
}
1 / i is a division expression between two integers, the result of which will be an int obtained by truncating the fraction part of the result. Since you are calculating float you can resolve it by using a 1f float literal
for (int i = 1; i < 100; i += 2) {
N = N + 1f / i;
T = T + 1f / (i + 1);
}
However your code currently counts the following:
Consider i = 1 for which you get T = 0.5 which you later subtract from N while you should be adding it as per your problem statement. One way to sole it is to write the code as:
float sum = 1;
for (int i = 2; i <= 100; i++) {
float term = 1f / i;
if (i % 2 != 0) {
term *= -1;
}
sum += term;
}
System.out.println(sum);
the question is to find the sum of this series
series
i used this code to solve it , but im not quite sure the logic is correct.
the noofterms is how many terms are going to be added
and x is the number that will be assigned to the variable.
does the logic seem correct?
public static double sumOfSeries(double x, int noofterms){
double evennumbers=1;
double oddnumbers=1;
double result=1;
// since the power of x starts from 1 , we start i from 1 and increment by 2
for (int i=1; i<noofterms; i+=2 ){
// we reset starting numbers so we start from them everytime
evennumbers = 1;
oddnumbers = 1;
// everytime the number increases by 2 when it is smaller than i+1
// ex when its equal to 2 , j = 3 , j+1 = 4 so it increments by 2
// when its 4 , j = 5 , j+ 1 = 6 , it increments
for (int j=2; j<=i+1; j+=2){
// multiply by increments of 2
evennumbers= evennumbers * j;
}
// it starts from 1 and increments by 2 so it goes like 1,3,5
for (int z=1; z<=i; z+=2){
oddnumbers = oddnumbers * z;
}
result*=((Math.pow(x, (double)i)) / (double)i) + (oddnumbers/evennumbers);
}
return result;
}
You can do it better. Note that numerators and denominators form two sequences, so you can keep previous terms to efficiently make computations, this will look like this :
long even = 1;
long odd = 1;
double result = x;
for(long i = 1; i < noofterms; i++)
{
even *= 2 * i;
odd *= 2 * i - 1;
double oper = Math.pow(x, (double)(2 * i + 1)) / (double)(2 * i + 1);
result += (double)even / (double)odd * oper;
}
You can improve by using logarithms because even and odd will grow very fast and will lead to overflows :
double even = 0.0;
double odd = 0.0;
double result = x;
double logx = Math.log(x);
for(long i = 1; i < noofterms; i++)
{
even += Math.log((double)(2 * i));
odd += Math.log((double)(2 * i - 1));
double oper = logx * (2 * i + 1) - Math.log((double)(2 * i + 1));
result += Math.exp(even - odd + oper);
}
EDIT: only one sequence could also be computed : p *= (double)(2*i)/(2*i-1). Then the log trick is not useful.
So I need to output a sum of factorials like 1!+2!...+n!=sum I found a way to get a single factorial but I don't know how to sum them together. This is my attempt at doing so:
System.out.println("Ievadiet ciparu");
Scanner in = new Scanner(System.in);
n = in.nextInt();
if ( n < 0 )
System.out.println("Ciparam jabut pozitivam.");
else
{
while (x>2){
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
sum=sum+fact;
n=n-1;
if (n==0) break;
}
System.out.println("Faktorialu summa "+sum);
Rather than have a loop 1-n and calculate each factorial elsewhere, I would accumulate the sum as you calculate the factorials - ie have two local variables; one for factorial and one for the sum:
long factorial = 1, sum = 0;
for (int i = 1; i <= n; i++) {
factorial *= i;
sum += factorial;
}
When tested with n = 5, sum is 153, which is correct: 1 + 2 + 6 + 24 + 120
Your problem was that the sum was outside the loop - you just needed braces like here.
Also, your while loop condition x < 2 will never change, so either the loop will never execute (if x > 1) or the loop will never terminate, because x is not changed within the loop.
hmmm my search for finding a recursive(via recursive method calling) version of these code still getting nowhere
`public static long factorialSum(long n){
long x = n;
for(int i = 1; i < n; i++){
x = (n-i)*(1+x);
}
return x;
}`
if you just look at the problem more closely you'll see you can do it in linear time, the trick is in (n-1)! + n! = (n-1)!*(1 + n), to understand this more deeply i recommend add (n-2)! just to see how it grows.
I couldn't figure out how the decrement operator (e--)
works in code below, so i wrote the other class below it
to get the same result. I want to know how the decrement operator
achieves that result in the Power class. - Newbie.
int result, e;
for(int i=0; i < 10; i++) {
result = 1;
e = i;
while(e > 0) {
result *= 2;
e--;
}
System.out.println("2 to the " + i +
" power is " + result);
}
Code written to achieve same result
int result = 1;
for(int i=0; i < 10; i++) {
if (i > 0) {
result*=2;
}
System.out.println("2 to the " + i +
" power is " + result);
}
So the first example is resetting result for each iteration of the main for loop, so it needs to recalculate from scratch each time, where as the second example is keeping the previous computed value. The if in the second example is not needed is it.
The decrement operator modifies the variable on which it's called. So e-- is effectively e = e - 1 (except the overall result of the expression is different, see below).
This code:
result = 1;
e = i;
while(e > 0) {
result *= 2;
e--;
}
starts with result = 1 and then loops for i iterations doubling the value in result. Equivalent code using for which you seem more comfortable with:
result = 1;
for (e = 0; e < i; e++) {
result *= 2;
}
There are two forms of the decrement (and increment) operator: Prefix and postfix, depending on whether the operator is before (prefix) or after (postfix) its operand. Either could be used in the code you were asking about, because the only difference is the result of the expression.
Prefix: Suppose we have x = 5. The expression --x has the value 4: First we decrement x, then we take its new value as the result of the expression.
Postfix: Suppose we had x = 5 (again). The expression x-- has the value 5, with x ending up containing 4: First we grab the current value of x as the result of the expression, then we decrement it (because the -- is after x).
int x, r;
x = 5;
r = --x; // Prefix
System.out.println("r = " + r + ", x = " + x); // "r = 4, x = 4"
x = 5;
r = x--; // Postfix
System.out.println("r = " + r + ", x = " + x); // "r = 5, x = 4"
i figure out that by placing a System.out.println(e) i could "see" the variable "e" behavior in order to make sense of the decrement.
class Power {
public static void main(String args[]) {
int e;
int result;
for(int i=0; i < 10; i++) {
result =1 ;
e = i;
while(e > 0) {
System.out.println(e); // not part of the original program
result *= 2 ;
e--;
System.out.println(e); // not part of the original program
}
//System.out.println("2 to the " + i +
//" power is " + result);
}
This is the output:
C:\Users\enrique\Desktop\Hello.java>java Power: 1, 0, 2, 1, 1, 0, 3
e = 1(iteration 1), 2^1, e (1) decremented to 0, e = 2 (iteration 2), 2^2, e(2) decremented to 1, e = 1 re-enter The while but is ignored as 2^1 is already registered, e (1) decremented to 0, e = 3 (iteration 3), 2^3…
I am making a program to prove Leibnitz method for computing PI.
(pi/4) = 1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 + ...
I took a very interesting approach to this and I am just wondering if there is a much easier way to do this.
What I did was I made the variable j the denominator. and the main idea was to have a counter start at -3 then go to Absolute value of -5 then -7 then absolute values of -9...so on. Do you think there is any way to make it smaller? Thanks :)
(To end the loop the teacher said to find the absolute difference and have that be < 1e-6)
public class Leibnitz
{
public static void main(String argv[])
{
double answer = (Math.PI) / 4; //answer
double numTheory = 1; //answer
double j = -3; //counts the Denominator
double piFrac; //extra variable for calc
int i = 0; //counts loop
System.out.print("How many iterations does it take to compute pi this series: ");
while (Math.abs(answer - numTheory) > 1e-6)
{
if (j % 4 == -1) //checks if number should be negative (5,9,... needs to be positive so -5 % 4 = -1, -9 % 4 = -1)
j = Math.abs(j);
piFrac = (1 / j); //fraction of pie
numTheory = numTheory + piFrac; //answer
if (j > 0) //makes counter a negative
j = -j;
j -= 2; //goes down by 2
i++; //counts how many times it goes thru the loop
}
System.out.println(i);
}
}
If you are just looking for optimizations. This should work, it's much shorter and not too much less readable.
while (Math.abs(answer + numTheory) > 1e-6)
{
j += 2;
numTheory += 1 / (++i % 2 == 0 ? -j : j);
}
Explanation, the code (++i % 2 == 0 ? -j : j) gets evaluated as follows
(expression) ? (if branch) : (else branch)
so in english. if (++i mod 2 equals 0) then do (-j) else do (j)
Full code:
public class Leibnitz
{
public static void main(String argv[])
{
double answer = Math.PI / 4; //answer
double numTheory = 1; //answer
double j = -3; //counts the Denominator
int i = 0; //counts loop
System.out.print("How many iterations does it take to compute pi this series: ");
while (Math.abs(answer + numTheory) > 1e-6)
{
j += 2;
numTheory += 1 / (++i % 2 == 0 ? -j : j);
}
System.out.println(i);
}
}