Question
We want to check part of Benford's Law, that the leftmost, first digit of each value in some well-known infinite integer sequences (factorial and Fibonacci)
We want to check part of Benford's Law, that the leftmost, first digit of each value in some well-known infinite integer sequences (factorial and Fibonacci) equals 1 about 30% of the time (in the asymptotic limit as more and more terms of the sequence are included).
Write a program (void main) that:
- Reads a positive integer from the user for the number of terms in each sequence (factorial and Fibonacci) to generate. Make it impossible for the user to enter invalid data to break your program, keep reading until they give you a valid positive integer. The first four test cases test for invalid input.
- Then generate terms in the factorial sequence, and for each term count how may have a first digit of one. See the starter code function header for function to return n! and write the method (assume 1!=1 is the first term). Note use of Java's BigInteger class (long is not large enough for large factorials). See the BigInteger API for how to create, do arithmetic, compare, and convert BigInteger objects. Also see starter code function header to return the leading digit of a BigInteger and write the method.
- Calculate the first digit 1 percentage and output a single line in this format (for n=100)
Output should look like this: Factorial first digit 1 percentage=30%
- Then do the same thing for the Fibonacci sequence (fib(1)=1 is the first term, don't count fib(0)=0) and calculate the first digit 1 percentage and output a single line in this format (for n=100)
Output should look like this: Fibonacci first digit 1 percentage=31%
Test case one: 1.4, -1.4, 100
Test case two: a, abc def, 100
Test case three: 0, -1, -10, 0, 100
Test case four: 9999999999999999, -9999999999999999, 100
Test case five: 500
Test case six: 1000
Start Code: import java.util.Scanner;
import java.math.BigInteger; import java.text.NumberFormat; public class Benfords { public static void main(String[] args) { NumberFormat pctFormat = NumberFormat.getPercentInstance();
}
public static BigInteger factorial(int n) {
}
public static BigInteger fib(int n) {
} public static int leadingDigit(BigInteger n) { }
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started