Fibonacci calculation - java

This program is supposed to get a Fibonacci number from the user and the program will calculate what it is while making sure that the user entered a positive number and a number no less than the Fibonacci number 70. So, if the user entered 7, it should print 13. The method fibcalc() is supposed to do the calculations.
When I try and compile the program, I get the errors "method fibcalc in class Fibonacci cannot be applied to given types: System.out.printf("Fibonacci #%d is %f", num, fibcalc(num, x3)); and "cannot find symbol" return x3;Here's my code:
import java.util.Scanner;
public class Fibonacci
{
public static void main ( String args[] )
{
Scanner input = new Scanner ( System.in );
int num;
double x3 = 0;
System.out.print("Which Fibonacci number would you like? ");
num = input.nextInt();
do
{
System.out.print("Which Fibonacci number would you like? ");
num = input.nextInt();
}while(num >= 0 && num <= 70);
System.out.printf("Fibonacci #%d is %f", num, fibcalc(num, x3));
}
public static double fibcalc(int num)
{
int x1 = 0;
int x2 = 1;
if (num == 0)
return 0;
else if (num == 1)
return 1;
else
for (int x3 = 0; x3 < num; x3++)
{
x3 = x1 + x2;
x1 = x2;
x2 = x3;
}
return x3;
}
}
There are probably other problems I've missed. I'm pretty new to java. Thanks in advance.

The fibcalc() method has a single int parameter, but you are calling it with two parameters.
Change the call from
fibcalc(num, x3)
to
fibcalc(num)
ie change that line to:
System.out.printf("Fibonacci #%d is %f", num, fibcalc(num));
Also, if you want accurate numbers for your results, change from using double to using BigInteger, which can handle arbitrarily large numbers accurately.

You can also use the following calculator to calculate the Fibonacci sequence (using Javascript): enter link description here

If you want to compute Fibonacci numbers, you can use direct (non-recursive, non-iterative) formula for Fibonacci numbers:
Fib(n) = (pow((1+sqrt(5))/2, n) + pow((1-sqrt(5))/2, n)) / sqrt(5)
It turns out that for all n >= 0, you can simplify this formula to:
Fib(n) = round(pow((1+sqrt(5))/2, n) / sqrt(5))
Knowing this, you can use following simple implementation for fibcalc:
public static double fibcalc(int num) {
return Math.floor(Math.pow((1+Math.sqrt(5))/2, num) / Math.sqrt(5) + 0.5);
}

Related

Count Multiples

I have been assigned to write a java program for class that counts multiples. The program takes three integers as input: low, high, x. The program then outputs the number of multiples of x between low and high exclusively.
If the input is: 1, 10, 2
the output would be: 5
My teacher has the proclivity to assign problems we haven't covered in class and I am unsure where to begin. Im not asking for the full code, just how to set up the problem
I am unsure of how to follow my logic thru the program: what I have so far is this
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int low, high, x;
int count = 0;
low = scnr.nextInt();
high = scnr.nextInt();
x = scnr.nextInt();
for(int i = low; i <= high; i++){
if(i % x == 0){
count++;
}
if (i % x != 0){
//System.out.println(count);// someone suggested to move this
}
}
System.out.println(count);
}
}
~~~~~~
If I input 1, 10, 2
My output is 01234
Moved the print of count outside of the loop... man I am tired.
FINAL EDIT: This code works, it accomplishes the goal. Thank you to #charisma and everyone else that helped me understand what was going on here. I am new to java but determined to learn more! Thanks all!!!!!
You can input numbers using scanner class similar to the following code from w3schools:
import java.util.Scanner; // Import the Scanner class
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}
low, high and x can be of data type int.
To check which numbers between low and high are multiples of x, you can use a for loop. You can declare a new variable count that can be incremented using count++ every time the for loop finds a multiple. The % operator could be useful to find multiples.
You can output using System.out.println(" " + );
Edit:
% operator requires 2 operands and gives the remainder. So if i % x == 0, it means i is a multiple of x, and we do count++.
The value of i will run through low to high.
for (i = low; i <= high; i++) {
if (i % x == 0) {
count++;
}
}
Once you get to the basic implementation (as explained by Charisma), you'll notice, that it can take a lot of time if the numbers are huge: you have high - low + 1 iterations of the loop. Therefore you can start optimizing, to get a result in constant time:
the first multiple is qLow * x, where qLow is the ceiling of the rational quotient ((double) low) / x,
the last multiple is qHigh * x, where qHigh is the floor of the rational quotient ((double) high) / x,
Java provides a Math.floor() and Math.ceil(), but you can get the same result using integer division and playing with the signs:
final int qLow = -(-low / x);
final int qHigh = high / x;
Now you just have to count the number of integers between qLow and qHigh inclusive.
return qHigh - qLow + 1;
Attention: if x < 0, then you need to use qLow - qHigh, so it is safer to use:
return x > 0 ? qHigh - qLow + 1 : qLow - qHigh + 1;
The case x == 0 should be dealt with at the beginning.
put count++; after the last print statement

My program does not output the right decimal numbers of an arithmetic average. How can I fix it?

I need to display the correct arithmetic average of a series of integers entered by the user.
If the user enters 6, 9, 7, and 4, the average should be 6.5 but instead displays 6.0. Why does that happen? I used an ArrayList to store all the integers.
import java.util.Scanner;
import java.util.*;
import java.util.Collections;
public class QuizScoreStatistics
{
public static void main(String[] args) {
List<Integer> Scores = new ArrayList<Integer>();
Scanner input = new Scanner(System.in);
int i = 0;
int a = 0;
while(a != 99) {
System.out.println("Enter scores");
a = input.nextInt();
if(a != 99) {
if ( a > 10 || a < 0) {
System.out.println("Score must be between 10 and 0");
}
else {
Scores.add(a);
}
i++;
}
}
int max = Collections.max(Scores);
int min = Collections.min(Scores);
int sum = 0;
double averg = 0;
for( i = 0; i <= Scores.size() - 1; i++) {
sum += Scores.get(i);
}
averg = sum / Scores.size();
System.out.println("Scores entered " + i);
System.out.println("Highest score " + max);
System.out.println("Lowest score "+ min);
System.out.println("Average: "+ averg);
}
}
I won't try to give away the entire question I think you could probably answer that yourself given a nudge in the right direction.
You correctly identified that your averg is a double because your answer could come out to something like 6.7 or 2.3 or whatever. Thats a correct assumption to make! However during your "arithmetic process" you are using integers to do the division, which will come out as an integer. I will repeat the actual DIVISION is happening with two integers , can you see where the bug is coming from?
If you need more of a push to see the exact remedy of this solution I would point you here
https://programming.guide/java/wrong-results-for-division.html
Try averg = (1.0 *sum) / Scores.size(); because int/int => int but double/int=>double
Ok, this is how the operator "/" works.
int / int => int
int / float => float
float / int => float
Since you are doing an int division (int/int), the result will be an int, losing decimal information. If you want your division to be float or double, you have two options, either you declare the sum as double or you can just cast the division, so it becomes a double division instead of an int division.
averg = (double) sum / Scores.size();

How to use a scanner in a while loop

I'm trying to create a method that will return the sum of the nth roots of each double x in numbers, where numbers consists of zero or more double tokens (separated by white space) and n is positive.
Examples: sumOfRoots("1.0 4.0 9.0 16.0", 2) is 10 and sumOfRoots("", 3) is 0.
public static double sumOfRoots (String numbers, int n)
{
Scanner scanner = new Scanner(numbers);
Scanner b = scanner.useDelimiter(" ");
int y = b.nextInt();
double x = 0;
while (b.hasNextDouble())
{
x = x + (y ^ (1 / n));
}
return x;
}
But I keep on throwing input mismatch errors. Any idea on what I can change to make it work?
If you wish to use Scanner, your code can be fixed like that:
public static double sumOfRoots(String numbers, int n){
Scanner scanner = new Scanner(numbers);
double sum = 0;
while(scanner.hasNextDouble())
sum += Math.pow(scanner.nextDouble(), 1d / n);
return sum;
}
In Java ^ is not an exponentional operator (as said in comments), so you have to use Math.pow()

Java program gives incorrect Taylor series term for function e^x

//java program that asks the user to input a number that e^x=1+x+x^2/2! +x^3/3!... e is a mathematical constant equal to 2.718...
import java.util.Scanner;
public class taylor_2 {
public static void main(String args[]) {
Scanner input=new Scanner(System.in);
double x; //input for x
double factorial=1; //initializes factorial
int counter=1; //initializes counter
double result=1; //initializes result
System.out.println("Enter non negative number"); //asks user to enter x
x=input.nextInt();
//output in while loop will continue to be generated if user doesn't entered a negative number
while(x<1){
System.out.println("I said entered a positive number");
x=input.nextInt();
}
while(x>counter){
factorial=factorial*counter;//factorial formula
result=result+(Math.pow(x,counter))/factorial; //equation for e^x=1+x+x^2/2! +x^3/3!
counter++;
}
System.out.println("Taylor series is " +result);//output for taylor equation e^x
}
}
Here is the output of my code:
Enter non negative number
2
Taylor series is 4.0
When I entered 2 , it should have outputted 7.3890560983 instead of 4.0 since e=2.718... and e^2=7.3890560983. What am I doing wrong?
The problem is that the Taylor series is not the same function that e^x.
It will return a function that is close to the function e^x.
For understanding it better, I recommend you to look the second picture of the next link:
https://en.wikipedia.org/wiki/Taylor_series
You can see in the previous picture that as n is getting larger the function is getting more accurate.
Your code's problem is that your x value is your n value, and this is not really true.
x: Must be the value you want to now e^x.
n: Is the accurate of your equation. Larger means more accurate.
So you must change while(x>counter) with while(n>counter), where n can be either a variable with the user selected accuracy, or a constant with your selected accurcy.
I think that until x=100, n=150 should work.
I hope that helps you! :)
There seems to be an answer here: EXP to Taylor series for c++, even though the algorithm is slightly different to yours. Here's its Java version:
public class TaylorSeries {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);
System.out.println("Enter x:");
double x = input.nextDouble();
double result = calcExp(x);
System.out.println("calcExp(x) = " + result);
System.out.println(" e^x = " + Math.pow(Math.E, x));
}
static double calcExp(double x) {
double eps = 0.0000000000000000001;
double elem = 1.0;
double sum = 0.0;
boolean negative = false;
int i = 1;
sum = 0.0;
if (x < 0) {
negative = true;
x = -x;
}
do {
sum += elem;
elem *= x / i;
i++;
if (sum > Double.MAX_VALUE) {
System.out.println("Too Large");
break;
}
}
while (elem >= eps);
return negative ? 1.0 / sum : sum;
}
}
The output:
Enter x:
2
calcExp(x) = 7.389056098930649
e^x = 7.3890560989306495
All credit should go to the answer here: EXP to Taylor series. I have only converted c++ code to Java

Calculate e^x without inbuilt functions in Java

I am a beginner in Java and currently going through the "how to think like a computer scientist" beginners book. I am stuck with a problem in the iteration chapter. Could anyone please point me in the right direction?
When I use math.exp, I get an answer that is completely different from the answer my code obtains.
Note, it's not homework.
Here's the question:
One way to calculate ex is to use the infinite series expansion
ex = 1 + x + x2 /2! + x3/3! + x4/4! +...
If the loop variable is named i, then the ith term is xi/i!.
Write a method called myexp that adds up the first n terms of this
series.
So here's the code:
public class InfiniteExpansion {
public static void main(String[] args){
Scanner infinite = new Scanner(System.in);
System.out.println("what is the value of X?");
double x = infinite.nextDouble();
System.out.println("what is the power?");
int power = infinite.nextInt();
System.out.println(Math.exp(power));//for comparison
System.out.println("the final value of series is: "+myExp(x, power));
}
public static double myExp(double myX, double myPower){
double firstResult = myX;
double denom = 1;
double sum =myX;
for(int count =1;count<myPower;count++){
firstResult = firstResult*myX;//handles the numerator
denom = denom*(denom+1);//handles the denominator
firstResult = firstResult/denom;//handles the segment
sum =sum+firstResult;// adds up the different segments
}
return (sum+1);//gets the final result
}
}
The assignment denom = denom*(denom+1) is going to give a sequence as follows: 1, 1*2=2, 2*3=6, 6*7=42, 42*43=...
But you want denom = denom*count.
Let's say in general we just want to print the first n factorials starting with 1!: 1!, 2!, 3!, ..., n!. At the kth term, we take the k-1th term and multiply by k. That would be computing k! recursively on the previous term. Concrete examples: 4! is 3! times 4, 6! is 5! times 6.
In code, we have
var n = 7;
var a = 1;
for (int i = 1; i <= n; i++ ) {
a = a*i; // Here's the recursion mentioned above.
System.out.println(i+'! is '+a);
}
Try running the above and compare to see what you get with running the following:
var n = 7;
var a = 1;
for (int i = 1; i <= n; i++ ) {
a = a*(a+1);
System.out.println('Is '+i+'! equal to '+a+'?');
}
There are several errors here:
firstResult should start from 1, so that it goes 1+x+x^2 instead of 1+x^2+x^3
As timctran stated you are not calculating the factorial in a correct way.
To wrap up you can simplify your operations to:
firstResult = firstResult * myX / (count+1);
sum += firstResult;
Edit:
- I ran the code and saw that Math.exp(power) is printed instead of Math.exp(x)
- My first item is wrong since sum is initialized to myX.
Why make it complicated? I tried a solution and it looks like this:
//One way to calculate ex is to use the infinite series expansion
//ex = 1 + x + x2 /2! + x3/3! + x4/4! +...
//If the loop variable is named i, then the ith term is xi/i!.
//
//Write a method called myexp that adds up the first n terms of this series.
import java.util.Scanner;
public class InfiniteExpansion2 {
public static void main(String[] args) {
Scanner infinite = new Scanner(System.in);
System.out.println("what is the value of X?");
double x = infinite.nextDouble();
System.out.println("what is the value of I?"); // !
int power = infinite.nextInt();
System.out.println(Math.exp(power));//for comparison
System.out.println("the final value of series is: " + myCalc(x, power));
}
public static double fac(double myI) {
if (myI > 1) {
return myI * fac(myI - 1);
} else {
return 1;
}
}
public static double exp(double myX, double myE) {
double result;
if (myE == 0) {
result = 1;
} else {
result = myX;
}
for (int i = 1; i < myE; i++) {
result *= myX;
}
return result;
}
public static double myCalc(double myX, double myI) {
double sum = 0;
for (int i = 0; i <= myI; i++) { // x^0 is 1
sum += (exp(myX, i) / fac(i));
}
return sum;
}
}
If you want to think like an engineer, I'd do it like this:
keep it simple
break it into pieces
stick closely to the task (like I named the var myI, not myPower - seems clearer to me, for a start - that way you won't get confused)
I hope you like it!
I tried a solution and it looks like this:
public class Fact {
public int facto(int n){
if(n==0)
return 1;
else
return n*facto(n-1);
}
}
}
import java.util.Scanner;
public class Ex {
public static void main(String[] args){
Fact myexp=new Fact();
Scanner input=new Scanner(System.in);
int n=1;
double e=1,i=0,x;
int j=1;
System.out.println("Enter n: ");
n=input.nextInt();
System.out.println("Enter x: ");
x=input.nextDouble();
while(j<=n)
{
int a=myexp.facto(j);
double y=Math.pow(x,j)/(double)a;
i=i+y;
++j;
}
e=e+i;
System.out.println("e^x= "+ e);
}
}

Categories