There is a famous story about a primary school teacher who wanted to occupy his
ID: 3676522 • Letter: T
Question
There is a famous story about a primary school teacher who wanted to occupy his students' time by making the children compute the sum of 1 + 2 + 3 + ... + 100 by hand. As the story goes, the teacher was astounded when one of the children immediately produced the correct answer: 5050. The student, a child prodigy, was Carl Gauss, who grew up to be one of the most famous mathematicians of the eighteenth century. Repeat Gauss's remarkable calculation by writing a program with a loop that will compute and print the above sum. After you have the program working, rewrite it so you can compute 1 + 2 + ... + n where n is any positive integer. Perhaps the first algorithm used for approximating the square root of S is known as the "Babylonian method", named after the Babylonians, or "Heron's method", named after the first-century Greek mathematician Heron of Alexandria who gave the first explicit description of the method. It can be derived from (but predates by 16 centuries) Newton's method. The basic idea is that if x is an overestimate to the square root of a non-negative real number S then S/x will be an underestimate and so the average of these two numbers may reasonably be expected to provide a better approximation. More precisely, assuming S is a positive number: 1. Make a guess at the answer (you can pick S/2 as your initial guess). 2. Compute r = S / guess. 3. Set new guess = (guess + r) / 2 4. Go back to step 2 until the last two guess values are within 1% of each other^1. Write a program that: 1. Inputs the value of S from the user. 2. Uses the Babylonian Algorithm to determine and output the square root of n.Explanation / Answer
GaussianSum.java
import java.util.Scanner;
public class GaussianSum {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number n");
int n=sc.nextInt();
long sum=0;
for(int i=1;i<=n;++i)
{
sum+=i;
}
System.out.println("Sum of numbers till "+n+" is "+sum);
}
}
sample output:
Enter the number n
200
Sum of numbers till 200 is 20100
BabylonianAlgo.java
import java.util.Scanner;
public class BabylonianAlgo {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number S whose square root you want to calculate");
int s=sc.nextInt();
float guess=s/2;
float r=0,oldGuess=0;
while(true)
{
if(Math.abs(guess-oldGuess)<(0.01*oldGuess))
{
break;
}
oldGuess=guess;
r=s/guess;
guess=(guess+r)/2;
}
System.out.println("Square root of "+s+" is "+guess);
}
}
sample output:
Enter the number S whose square root you want to calculate
361
Square root of 361 is 19.00005
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.