My assignment was to calculate Pi using an algorithm he gave us in class, determine correct digits, and estimate Pi to six digits using a while loop and a recursive method. But my "super smart professor" didn't tell us a bloody thing about recursive methods and when I email him, he gets angry at me for not getting it just by looking at it. This is my code so far, I left out my while loop method and recursive method because I have no idea how to do those.
public static final double REAL_PI = 3.14159;//PI is the value prof gave us on the handout
public static double Pi = 0; //Pi is the value of Pi that this program calculates
public static int m = 0;
public static void main (String [] args)
{
Algorithm(); //calls on method of calculating pi
System.out.println("Calculated pi: " + Pi); //prints out pi
countDigits(Pi); //calls on countdigits method
System.out.println("Number of digits: " + c); //has the computer print out the count because that's how many digits are the same
PiRecur(); //calls on estimate digits method
}
public static double Algorithm() //should return a double (pi)
{
for(m=1; m<=100000; m++)
{
Pi += 4*(Math.pow(-1, m-1)/((2*m)-1));//Math.pow uses math package to calculate a power to use the algorithm
}
return Pi;
}
public static int countDigits (double Pi)
{
int a = (int) Pi; //the int cast makes Pi and REAL_PI into integers so the program can compare each digit separately
int b = (int) REAL_PI;
int c = 0;
int count = 0;
while(a == b)//if m less then or equal to 100,000 then while loop runs
{
count ++;
a = (int) (Pi*(Math.pow(10,count))); //if a=b then the computer will multiply Pi and REAL_PI by 10
b = (int) (REAL_PI*(Math.pow(10,count)));
/*when you input a and b
* while loop compares them
* if a = b then loop continues until a doesn't equal b and loop ends
*/
}
c = count; //gives c the value of the count so it can be used outside the method
return count;
}
}
I'm not sure how a solution that uses a while loop and recursion would loop like, since I can't read your professor's mind, but I can think of two different solutions that use one or the other.
Using while loop :
You don't run your algorithm an arbitrary number of iterations (100000 in your example) and hope that you got close enough to the expected result. You use a while loop, and on each iteration you check if your current calculation of Pi is close enough to your target.
public static double Algorithm()
{
int m = 1;
double Pi = 0.0;
while (countDigits(Pi) < 6) {
Pi += 4*(Math.pow(-1, m-1)/((2*m)-1)); // I'm assuming this formula works
m++;
}
return Pi;
}
Using recursion :
The same solution can be translated into a recursion. This time, you supply an initial index m (1) and an initial value of Pi (0) to Algorithm. The method adds the m'th term to Pi. If the new value of Pi is not good enough (determined by countDigits), you make a recursive call that would add the m+1th term to Pi and check again if the new value is good enough. The recursion would stop when the value of Pi is 6 digits accurate.
public static double Algorithm(int m,double Pi)
{
Pi += 4*(Math.pow(-1, m-1)/((2*m)-1));
if (countDigits(Pi) < 6)
Pi += Algorithm(m+1,Pi);
return Pi;
}
You call the method with :
Algorithm (1,0.0);
Related
I'm trying to figure out how to answer this question for my Java class, using only while loops:
Write an application that computes the value of mathematical constant e^x by using the following formula. Allow the user to enter the number of terms to calculate. e^x = 1 + (x/1!) + (x^2/2!) + (x^3/3!) + ...
I can't figure out how I would do this without also asking the user for a value for x? Below is the code that I created for calculating x with the number of terms and just the number 1 for the exponent of each fraction. Any help is appreciated
import java.util.Scanner;
public class FactorialB {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int counter = 0;
float answer = 0;
System.out.print("Enter number of terms: ");
int n = scanner.nextInt();
while (counter < n) {
double factorial = 1;
int factCounter = counter;
while (factCounter > 1) {
factorial = factCounter * factorial;
factCounter--;
}
answer += 1 / factorial;
counter++;
}
System.out.printf("e = %f%n", answer);
}
}
Firstly the question you seem to be asking:
There is no way to make a program that will give e for a specific number unless you ask the user for that number.
However it might be that they just want you to make a method that provides the solution (if it were called) independently of user input. (because the code to get user input isn't very interesting, what is interesting is how you reach the result).
An alternative way to provide x and n are for instance passing them as commandline arguments. (args[] in your main would be a way to provide them)
I would create a separate method that receives x and n that covers the main calculation:
e^x = 1 + (x/1!) + (x^2/2!) + (x^3/3!) + ...
And separate methods that cover 'calculating a single term (x^1/1!), (x^2/2!), etc' and 'factorialize(n)'
public void calculatePartialE_term(int x, int n) {
if (n == 0) {
return 1; // this will allow you to use a while loop, covers the n = 0 case
} else {
// removed the implementation, but basically do
// x^n/n! here for whatever value of n this term is calculating.
}
}
public int calcualteNFactorial(int n) {
// assert n >= 1
// use a while loop to calculate n factorial
}
the benefit of doing this in a separate methods is that you can prove / verify the working of calculatePartialE_term or calcualteNFactorial independently of one another.
now you can simply write a while loop based on x and n to do something like
public int calculateE_to_x(int x, int n) {
int current = 0;
int sum = 0;
while (current <= n) {
sum += calculatePartialE_term(x, current);
}
}
I wouldn't expect your teacher to expect you to show code that handles user input but even if that is the case it will be easier for them to verify your work if the actual work (of calculating) is done in a separate method.
This code is for finding the smallest number divisible by all num from 1 to 20
I dont understand how this code works on recursion can u pleases explain this it wil be helpful
static long gcd(long a, long b)
{
if(a%b != 0)
return gcd(b,a%b);
else
return b;
}
// Function returns the lcm of first n numbers
static long lcm(long n)
{
long ans = 1;
for (long i = 1; i <= n; i++)
ans = (ans * i)/(gcd(ans, i));
return ans;
}
// Driver program to test the above function
public static void main(String []args)
{
long n = 20;
System.out.println(lcm(n));
}
This is very mathy, but gcd stands for "greatest common denominator" and lcm stands for "lowest common multiple".
The main algorithm keeps track of the current lowest common multiple "ans", and iterates "i" from 1 to "n" which in this case is 20. It then multiplies the current value by each "i" and divides by the greatest common denominator between "ans" and "i".
The gcd() method uses Euclid's algorithm to calculate the greatest common denominator
The reason that algorithm works is more a question for https://math.stackexchange.com/
I was playing around with a few practice problems in Java. I wrote a recursive program for program given below. My solution is right except for the suspended (which I believe) gets back to active state and changes the value of the recursive method. I have also added a screenshot of Eclipse in debug mode where the thread stack is shown.
package com.nix.tryout.tests;
/**
* For given two numbers A and B such that 2 <= A <= B,
* Find most number of sqrt operations for a given number such that square root of result is a whole number and it is again square rooted until either the
* number is less than two or has decimals.
* example if A = 6000 and B = 7000, sqrt of 6061 = 81, sqrt of 81 = 9 and sqrt of 9 = 3. Hence, answer is 3
*
* #author nitinramachandran
*
*/
public class TestTwo {
public int solution(int A, int B) {
int count = 0;
for(int i = B; i > A ; --i) {
int tempCount = getSqrtCount(Double.valueOf(i), 0);
if(tempCount > count) {
count = tempCount;
}
}
return count;
}
// Recursively gets count of square roots where the number is whole
private int getSqrtCount(Double value, int count) {
final Double sqrt = Math.sqrt(value);
if((sqrt > 2) && (sqrt % 1 == 0)) {
++count;
getSqrtCount(sqrt, count);
}
return count;
}
public static void main(String[] args) {
TestTwo t2 = new TestTwo();
System.out.println(t2.solution(6550, 6570));
}
}
The above screenshot is from my debugger and I've circled the Thread stack. Can anyone try and run the program and let me know what the problem is and what would be the solution? I could come up with a non recursive solution.
Your recursion is wrong, since the value of count will return in any case 0 or 1 even if it goes deep down into recursive calls. Java is pass by value, meaning that modifying the value of a primitive inside of a method wont be visible outside of that method. In order to correct this, we can write the following recursion:
private int getSqrtCount(Double value) {
final Double sqrt = Math.sqrt(value);
if((sqrt > 2) && (sqrt % 1 == 0)) {
return getSqrtCount(sqrt) + 1;
}
return 0;
}
Your code is wrong, you should have
return getSqrtCount(sqrt, count);
instead of
getSqrtCount(sqrt, count);
Otherwise the recursion is pointless, you're completely ignoring the result of the recursion.
I've been given the following assignment and my code isn't working. The question is:
Using a while or a do-while loop, write a program to compute PI using the following equation: PI = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) - 4/(8*9*10) + ... Allow the user to specify the number of terms (5 terms are shown) to use in the computation. Each time around the loop only one extra term should be added to the estimate for PI.
This is the code I have so far:
import java.util.Scanner;
import javax.swing.JOptionPane;
import java.lang.Math;
public class LabFriday25 {
public static void main(String[] args) {
String termInput = JOptionPane.showInputDialog(null, "How many terms of
PI would you like?");
Scanner termScan = new Scanner (termInput);
double termNum = termScan.nextDouble();
double pi = 3;
int count = 0;
double firstMul = 2;
double secMul = 3;
double thirdMul = 4;
double totalMul = 0;
while (count<= termNum)
{
if (termNum==1)
{
pi = 3.0;
}
else if (count%2==0)
{
totalMul= (4/(firstMul*secMul*thirdMul));
}
else
{
totalMul = -(4/((firstMul+2)*(secMul+2)*(thirdMul+2)));
}
pi = pi + (totalMul);
firstMul = firstMul + 2;
secMul = secMul + 2;
thirdMul = thirdMul + 2;
//totalMul = (-1)*totalMul;
count++;
}
JOptionPane.showMessageDialog(null, "The value of pi in " + termNum + " terms is : " + pi);
}
}
I can't figure out why the code won't return the right value for 3 or more terms of Pi, it keeps giving the same value every time.
EDIT: I removed the semi-colon from the end of the while statement and now the code is returning the value 3.0 for any number of terms inputted by the user. Where am I going wrong?
EDIT2: Removed condition from while loop. Answers are closer to being correct, but still not accurate enough. How can I correct this to give me the right answer?
The semi-colon at the end from the while statement is evaluated independently causing the body of the loop to execute unconditionally so the result is always the same
while (count > 0 && count <= termNum);
^
In addition the loop is terminating after the first iteration. Remove the first expression from the loop, i.e.
while (count <= termNum) {
I just gave a coding interview on codility
I was asked the to implement the following, but i was not able to finish it in 20 minutes, now I am here to get ideas form this community
Write a function public int whole_cubes_count ( int A,int B ) where it should return whole cubes within the range
For example if A=8 and B=65, all the possible cubes in the range are 2^3 =8 , 3^3 =27 and 4^3=64, so the function should return count 3
I was not able to figure out how to identify a number as whole cube. How do I solve this problem?
A and B can have range from [-20000 to 20000]
This is what I tried
import java.util.Scanner;
class Solution1 {
public int whole_cubes_count ( int A,int B ) {
int count =0;
while(A<=B)
{
double v = Math.pow(A, 1 / 3); // << What goes here?
System.out.println(v);
if (v<=B)
{
count=count+1;
}
A =A +1;
}
return count ;
}
public static void main(String[] args)
{
System.out.println("Enter 1st Number");
Scanner scan = new Scanner(System.in);
int s1 = scan.nextInt();
System.out.println("Enter 2nd Number");
//Scanner scan = new Scanner(System.in);
int s2 = scan.nextInt();
Solution1 n = new Solution1();
System.out.println(n.whole_cubes_count (s1,s2));
}
}
Down and dirty, that's what I say.
If you only have 20 minutes, then they shouldn't expect super-optimized code. So don't even try. Play to the constraints of the system which say only +20,000 to -20,000 as the range. You know the cube values have to be within 27, since 27 * 27 * 27 = 19683.
public int whole_cubes_count(int a, int b) {
int count = 0;
int cube;
for (int x = -27; x <= 27; x++) {
cube = x * x * x;
if ((cube >= a) && (cube <= b))
count++;
}
return count;
}
For the positive cubes:
i = 1
while i^3 < max
++i
Similarly for the negative cubes but with an absolute value in the comparison.
To make this more general, you need to find the value of i where i^3 >= min, in the case that both min and max are positive. A similar solution works if both min and max are negative.
Well, it can be computed with O(1) complexity, we will need to find the largest cube that fits into the range, and the smallest one. All those that are between will obviously also be inside.
def n_cubes(A, B):
a_cr = int(math.ceil(cube_root(A)))
b_cr = int(math.floor(cube_root(B)))
if b_cr >= a_cr:
return b_cr - a_cr + 1
return 0
just make sure your cube_root returns integers for actual cubes. Complete solution as gist https://gist.github.com/tymofij/9035744
int countNoOfCubes(int a, int b) {
int count = 0;
for (int startsCube = (int) Math.ceil(Math.cbrt(a)); Math.pow(
startsCube, 3.0) <= b; startsCube++) {
count++;
}
return count;
}
The solution suggested by #Tim is faster than the one provided by #Erick, especially when A...B range increased.
Let me quote the ground from github here:
"one can notice that x³ > y³ for any x > y. (that is called monotonic function)
therefore for any x that lies in ∛A ≤ x ≤ ∛B, cube would fit: A ≤ x³ ≤ B
So to get number of cubes which lie within A..B, you can simply count number of integers between ∛A and ∛B. And number of integers between two numbers is their difference."
It seems perfectly correct, isn't it? It works for any power, not only for cube.
Here is my port of cube_root method for java:
/*
* make sure your cube_root returns integers for actual cubes
*/
static double cubeRoot(int x) {
//negative number cannot be raised to a fractional power
double res = Math.copySign(Math.pow(Math.abs(x), (1.0d/3)) , x);
long rounded_res = symmetricRound(res);
if (rounded_res * rounded_res * rounded_res == x)
return rounded_res;
else
return res;
}
private static long symmetricRound( double d ) {
return d < 0 ? - Math.round( -d ) : Math.round( d );
}
I am aware of Math.cbrt in java but with Math.pow approach it is easy to generalize the solution for other exponents.