Write a program that reads doubles, find the square root for each number also yo
ID: 3633450 • Letter: W
Question
Write a program that reads doubles, find the square root for each number also you must list all prime factors.Sample:
Input must be entered such a format :
Enter numbers (0 for Exit): 16 8 9 12 0
Output must be:
The square root of 16 is 4
Prime factors of 16 are 2
The square root of 8 is 2.8
Prime factors of 8 are 2
The square root of 9 is 3
Prime factors of 9 are 3
The square root of 12 is 3.46
Prime factors of 12 are 2, 3
You are not allowed to use Math.sqrt().
just use import java.util.Scanner;
p.class
p.class static void main
...
Explanation / Answer
Hi, I think you'll find this follows your requirements. Give it a read and test it out a couple of times to understand how it works. I commented the important stuff. Also, I use a little trick in printing out the square root because doubles are ridiculous to print with 6 - 10 digits of precision, so that's a cheap trick to cut it to smaller precision without using java Math methods.
I hope it helps, please remember to rate :)
import java.util.Scanner;
public class MyClass {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double number;
System.out.print(" Enter numbers (0 for Exit): ");
do
{
number = scanner.nextDouble();
if(number != 0)
{
// ============= COMPUTING SQUARE ROOT ===============
// get Square root using Babylonian method
double estimate=number;
double divisor=2;
for(int i=0; i<100; i++)
{
estimate=number/divisor;
estimate=(estimate+divisor)/2; //find average estimate & divisor
divisor=estimate;
}
double sqrt = estimate;
// if sqrt is a full integer - print it as is
if(sqrt % 1 == 0)
{
System.out.println("The square root of " + (int)number
+ " is " + (int)sqrt );
}
// else, the sqrt to limit it to 2 decimal places
else
{
// scale it
int x = (int)(sqrt * 100.0);
double formatedSqrt = ((double)x)/100.0;
System.out.println("The square root of " + (int)number
+ " is " + formatedSqrt );
}
// ============= COMPUTING PRIME FACTORS ===============
// List all prime factors of number
System.out.print("Prime factors of " + (int)number + " are ");
for(int i = 2; i <= number; i++)
{
if(number % i == 0)
{
if(i == 2)
System.out.print(" " + i);
else
{
boolean isPrime = true;
for(int j = 2; j < i; j++)
{
if(i % j == 0)
isPrime = false;
}
if(isPrime)
System.out.print(" " + i);
}
}
}
System.out.print(" ");
}
}while(number != 0);
}// end of main method
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.