Print fibonacci up to user entered number - java

I'm trying to print the Fibonacci series up to whatever number the user types in. The problem is that my code ends up printing that amount of numbers. If a user enters 100, I want the code to stop at 100, but my code prints 100 numbers. Also, I'm supposed to have printf and a while statement. I don't even know how to use printf.
package l12;
import java.util.Scanner;
public class L12 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.println("Enter an integer: ");
int n = console.nextInt();
System.out.println("The Fibonacci numbers less than " + n + " are: ");
for(int i=1; i<=n; i++){
System.out.print(fibonacci(i) +" ");
}
}
public static int fibonacci(int n){
if(n == 1 || n == 2){
return 1;
}
int f1=1;
int f2=1;
int fibonacci=1;
for(int i= 3; i<= n; i++){
do { fibonacci = f1 + f2;
f1 = f2;
f2 = fibonacci;
}
while (fibonacci <= n);
}
return fibonacci;
}
}

A simple way of doing it would be :
public static void main(String [] args){
Scanner console = new Scanner(System.in);
System.out.println("Enter an integer: ");
int n = console.nextInt();
if(n>1) {
System.out.println("The Fibonacci numbers less than " + n + " are: ");
System.out.print("1, 1, ");
int f2=1;
int fibonacci=1;
for(int i=1; i+f2 < n;){
fibonacci = i + f2;
i = f2;
f2 = fibonacci;
System.out.print(fibonacci+", ");
}
} else {
System.out.println("There are no numbers less than " + n + " in the series");
}
}

If I understand your question, then you could change this (which stops when i > n)
for(int i=1; i<=n; i++){
System.out.print(fibonacci(i) +" ");
}
to something like this, which stops when the result of fibonacci(i) > n, stores the result in fib and uses printf (the Format String syntax says that with d The result is formatted as a decimal integer).
int fib;
for (int i = 1; (fib = fibonacci(i)) <= n; i++) { // <-- stop wehn fib >= n
System.out.printf("%d ", fib); // <-- printf.
}
System.out.println(); // <-- Add a new-line.

I will be giving you an answer in Go so if you watch closely, you'll see the following sequence:
1 1 2 3 5 8 13 21 34 55 89 144 ...
The formula for mapping the Fibonacci sequence is:
Then if you code this (Go):
package main
import "fmt"
func fibonacci() func() int {
first, second := 0, 1
return func() int {
ret := first
first, second = second, first+second
return ret
}
}
func main() {
f := fibonacci()
for i := 0; i < /* What users enter */; i++ {
fmt.Println(f())
}
}
You'll see the numbers till entered by user. I hope that approach helped you understand better the problem!
Cheers!

This prints 100 numbers because you are looping n times no matter what:
for(int i=1; i<=n; i++){
System.out.print(fibonacci(i) +" ");
}
I would recommend changing this to a do-while loop as well:
int i = 1;
int fib;
do{
fib = fibonacci(i);
System.out.print(fib + " ");
} while(fib < n);
The above code, as I hinted at, is always going to loop 100 times. Even though your fibonacci method doesn't let it exceed 100, your for loop is still going to print 100 numbers.

Related

How can I count odd digits in java, but if that number has more then one odd digit count the first one only

I want to make a program that implements an array of numbers and if that array has an odd digit in it add it to the sum. For example 123(has 1 and 3 as odd digits) 222(no odd digits) and 434(has 3 as a odd digit). The end sum should be 123+434. This is what I came up with but the sum would be 123+123+434(Sice 123 has 2 odd numbers it counts it two times)
import java.util.Scanner;
public class Ex4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int sum = 0;
System.out.print("Number of numbers: ");
int j = sc.nextInt();
System.out.println("List of numbers: ");
int arr[] = new int[j];
for(int i = 0; i < j; i++){
arr[i] = sc.nextInt();
}
for(int i = 0; i < j; i++)
{
int num = arr[i];
while (num > 0) {
System.out.println(num % 10);
if (num%2!=0)
{
sum= sum+arr[i];
System.out.println("SUM IS: "+sum);
}
num = num / 10;
}
}
}
}
If you don't want to add the same number multiple times, just break out of the while loop as soon as you add it the first time.
while (num > 0) {
System.out.println(num % 10);
if (num%2!=0)
{
sum = sum+arr[i];
System.out.println("SUM IS: "+sum);
break; // add this line
}
num = num / 10;
}
The break statement immediately ends the loop it is inside of (regardless if it is a for, while or a do ... while loop).
There is also a continue statement (which you don't need here), that immediately continues to the next loop iteration, skipping the execution of any code after the continue statement that is part of the loop.

Prime problems java

A prime number is a positive integer greater than 1 that is divisible only by itself and 1. In this assignment you are responsible to write a complete Java program to display first N prime numbers. In other words, your program should list the first N prime numbers.
Functional Requirements
Your program should prompt the user for a positive number, or a value of -1 to terminate the program. If the user enters 0, or a negative number, the program will also end immediately.
Your program will display the first N prime numbers given by the user. For example, if the user enters 3, the program should display: “2, 3, 5” which are the first three prime numbers. If the user enters 6, the output would be: “2, 3, 5, 7, 11, 13”.
Sample Run
Welcome to the list of N prime numbers program!
===============================================
Please enter the value of N (positive integer):
6
First 6 prime numbers are:
2
3
5
7
11
13
When i worked on it i got this but need help finishing
import java.util.Scanner;
public class prime {
public static void main(String[] args) {
System.out.print("Welcome to the list of N prime numbers program! \n========================================================\nPlease enter the value of N (positive integer): ");
Scanner scan = new Scanner(System.in);
int n;
int status=1;
int num=3;
n = scan.nextInt();
if(n>=1) {
System.out.println(2);
for(int count=2; count<=n; count++) {
for(int j=2; j<=Math.sqrt(num);j++) {
if(num%j==0) {
status =0;
break;
}
if(status!=0) {
System.out.println(num);
count++;
}
}
status=1;
num++;
}
}
}
}
you should give a out.println("enter the number of prime numbers needed");
then read it using scanner(for example if it is reading into x) and provide a if condition as
if(x<=0)
{
break;
}
and balance code can be given in the else condition.
public class prime {
public static boolean isPrime(int n) {
for(int j=2; j<=Math.sqrt(n)+1;j++) { //Math.sqrt(n) + 1 because you want to check more than half of the original value.
if(n%j==0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.print("Welcome to the list of N prime numbers program! \n========================================================\nPlease enter the value of N (positive integer): ");
Scanner scan = new Scanner(System.in);
int inputNum; //try making the variable name meaningful
inputNum = scan.nextInt();
int count = 0;
int startingVal = 2;
while(count<inputNum) {
if(inputNum==-1) {
break;
}
if(count==0) {
System.out.println(2);
count++;
}
else if(isPrime(startingVal)) {
System.out.println(startingVal);
count++;
}
startingVal ++;
}
}
}
This should work fine. As #Amadan in the comment section already mentioned, your program did not work because your if(status!=0) is in the for loop.
Also, setting the variable names meaningful helps you fix or edit your code easier.
please use below method to get prime no.
static List<Integer> nthPrimeNo(int nth){
List<Integer> integers = new ArrayList<>();
int num, count, i;
num=2;
count=0;
for (int j = 0; j < nth; j++) {
while (count < j){
num=num+1;
for (i = 2; i <= num; i++){
if (num % i == 0) {
break;
}
}
if ( i == num){
count = count+1;
}
}
integers.add(num);
}
return integers;
}
Or do you want to get 10 greater than primes number,
static List<Integer> sieveOfEratosthenes(int n) {
boolean prime[] = new boolean[n + 1];
Arrays.fill(prime, true);
for (int p = 2; p * p <= n; p++) {
if (prime[p]) {
for (int i = p * 2; i <= n; i += p) {
prime[i] = false;
}
}
}
List<Integer> primeNumbers = new LinkedList<>();
for (int i = 2; i <= n; i++) {
if (prime[i]) {
primeNumbers.add(i);
}
}
return primeNumbers;
}
use this function call System.exit(0); in exit condition

How do I get the sum of the first two sequences when the user enters "2" as "n"?

The sequence is: sum = 1 + 1/2 + 1/4 + 1/9 + 1/16 + 1/25+...
When I enter "2" it just gives me the sum of 1.25. How do you get it so when "2" is entered, it is adding 1 + 1/2?
Oh and I'm in an entry level java course so I we cant use arrays or anything that advance yet.
Thanks in advance!
import java.util.Scanner;
public class Sum
{
public static void main(String[] args)
{
//declarations
Scanner scan = new Scanner(System.in);
double sum = 0;
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
//process
for(int counter = 1; counter <= n; counter += 1)
{
sum += 1.0 / (counter*counter);
}
System.out.println("The sum is: " + sum);
}
}
Since you say that 1/2 must be part of the sequence, so be it. (But that's a bizarre sequence and I strongly suggest that you double check this with your professor.) I'll assume that the remainder of the sequence is defined by 1/i2. Note that with these assumptions, the sequence terminates at 1/(n-1)2 rather than 1/n2.
You'll need special handling for the cases n == 1 and n > 1. One possibility is to initialize sum to 1 if n == 1; initialize it to 1.5 if n > 1; and otherwise initialize it to 0. Then start the loop at counter = 2 and change the loop termination condition to counter < n (instead of <=).
You need to manage "1" and "2" as special cases.
import java.util.Scanner;
public class Sum
{
public static void main(String[] args)
{
//declarations
Scanner scan = new Scanner(System.in);
double sum = 0;
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
//process
for(int counter = 1; counter <= n; counter += 1)
{
if (counter == 1)
sum = 1;
else if (counter == 2 )
sum += 1.0/((counter-1)+(counter-1));
else
sum += 1.0 / ((counter-1)*(counter-1));
}
System.out.println("The sum is: " + sum);
}
}
If that's your sequence then you should really start by setting the sum equal to 1.5 and then rest of it will work. Your sequence should be a geometric sequence 1/n^2 I think it's a mistake.
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
double sum = 1.5;
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
if(n==1)
System.out.println("The sum is: " + 1);
//process
for(int counter = 2; counter <n; counter++) {
double mul = counter*counter;
sum += 1.0/mul ;
}
System.out.println("The sum is: " + sum);
}
Output :
Enter n:
2
The sum is: 1.5
Enter n:
3
The sum is: 1.75
The following code will solve your problem, i have used Math.pow() to get the sequence running and not multiplying it twice.
public static void main(String[] args) throws UnknownHostException {
//declarations
Scanner scan = new Scanner(System.in);
//to generate this sequence we take the first two as constants and start generating from the third onwards
double first = 1;//first number in the sequence
double second = 0.5;//second number in the sequence
double sum = first+second;//adding first and second
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
if(n==1){
System.out.println("The sum is: " + first);
return;
}
if(n==2){
System.out.println("The sum is: " + sum);
return;
}
//process
for(int counter = 2; counter <n; counter += 1)
{
sum += 1.0 / Math.pow(counter, 2);//will be computed when you enter values when n is more than 3
}
System.out.println("The sum is: " + sum);
}
As per your for loop, the sequence generated will be 1 + 1/(2*2) + 1/(3*3)+ ......
So, when you enter 2 => 1+1/(2*2) = 1+0.25=1.25.
Otherwise, your logic is Good. you can implement few exceptions, but as you mentioned that you re new to Java, you ll slowly encounter them.
Happy Learning Java :)

How to sum powers of 2 with while loop

I need to calculate the sum of 2^0+2^1+2^2+...+2^n, where n is a number entered by the user. The main problem is that I don't know how to use the while loop to sum the different result of 2^n up.
Here is what I've tried:
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
while(power <= i) {
Math.pow(number, i);
sum = sum + Math.pow(number, i);
i = i + 1;
}
int result = (int)Math.pow(number, i);
System.out.println("The sum is: " + result);
}
}
Only you have to do is:
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
double sum = Math.pow(2,power+ 1 ) - 1;
System.out.println("The sum is: " + sum);
}
}
In this link explains the math expresion
All fine, just a few changes.
Change the parts code to
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
/*Remove this --------> while(power <= i) {*/
while (i <= power) {//it should be this
/*Remove this -------> Math.pow(number, i);*/
sum = sum + Math.pow(number, i);
i = i + 1;
}
System.out.println("The sum is: " + sum);
Your conditional is backwards, it should read:
while (i <= power)
You compute the sum of powers, then completely ignore it, just printing out the result of 2^i. you should be printing out sum, something like:
while (i <= power) {
sum += Math.pow(number, i);
i++;
}
System.out.println("The sum is: " + sum);
For style points this won't handle a negative power, so you'll need to test for that.
Dont understand why do you want to loop in this case. You can do it like :
System.out.println("The sum is: "+(Math.pow(2, power+1)-1 ));
But if you really want to use loop try this :
Scanner reader = new Scanner(System.in);
System.out.println("Type a power: ");
int power = Integer.parseInt(reader.nextLine());
int number = 2;
int i = 0;
double sum = 0;
while(i<=power) {
sum = sum + Math.pow(number, i);
i = i + 1;
}
int result = (int)Math.pow(number, i);
System.out.println("The sum is: " + sum);
Here is a solution with comments to explain the logic. While loops need some kind of variable to control the number of iterations. That variable of course needs to be updated somewhere inside the loop.
You can compute the sum of the powers with the Math.pow() function, obviously. No import statement is needed to use it. I hope this helps. Good luck.
/* Scanner and variable to get and hold user input */
Scanner scan = new Scanner( System.in );
int userInput = 0;
/* Variable to hold the sum, initialized to 0.0 */
double sum = 0.0;
/* Prompt the user, and obtain the reply */
System.out.print( "Enter the exponent: ");
userInput = scan.nextInt();
/* The while loop and it's initialized counter */
int counter = 0;
while( counter <= userInput ){
/* Add each power to sum using Math.pow() */
sum = sum + Math.pow( 2, counter );
/* Watch the output as the loop runs */
System.out.println( "Sum: " + sum );
counter++; // Increment counter, so the loop exits properly
} // End while loop
public class SumofSquare {
public static void main(String[] args) {
// TODO Auto-generated method stub
String c = "123";
char d[] = c.toCharArray();
int a[] = new int[d.length + 1];
for (int i = 0; i < d.length; i++)
a[i] = d[i] - 48;
int r = 0;
for (int i = 0; i < c.length(); i++)
r = r + (int) Math.pow(a[i], a[i + 1]);
System.out.println(r);
}
}
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
int power=Integer.parseInt(reader.nextLine());
int number=2;
int i=0;
int result=0;
while (power>=i) {
result += (int)Math.pow(number, i);
i++;
}
System.out.println("The result is "+result);
}
}
import java.util.Scanner;
public class SumOfThePowers {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a number:");
double power=Double.parseDouble(reader.nextLine());
int number=2;
int i=0;
double sum=0;
while (power>=i) {
sum=sum+Math.pow(number, i);
i++;
}
System.out.println("The sum is "+sum);
}

Trying to add sum of all even integers between 2 and the input, and I just get the input back

I'm attempting to write something for an assignment that takes the sum of all the even integers between 2 and the number entered by the user and prints it. If it is below 2 it should return an error. I'm getting an error for anything under 2, however, when I go have it return the sum it just returns the input.
I think I may have messed a variable up in this loop, but I can't see where I went wrong.
import java.util.Scanner;
public class EvenSum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number larger than 2");
int num = input.nextInt();
if (num >= 2) {
int sum = 0;
for (int i = 2; i <= num; i +=2) {
sum += i;
}
System.out.println("The sum of all even numbers between 2 and the input is " + num);
} else {
System.out.println("Invalid, please enter a number above 2");
}
}
}
System.out.println("The sum of all even numbers between 2 and the input is " + num);
should be
System.out.println("The sum of all even numbers between 2 and the input is " + sum);
There is a formula to compute the answer without a loop, by the way. But perhaps that is not the point of the exercise?
It's because you return num instead of sum
Declare sum outside if statement, and print sum instead of num
package com.test;
import java.util.Scanner;
public class EvenSum {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter a number larger than 2");
int num = input.nextInt();
int sum = 0;
if (num >= 2) {
for (int i = 2; i <= num; i += 2) {
sum += i;
}
System.out
.println("The sum of all even numbers between 2 and the input is "
+ sum);
} else {
System.out.println("Invalid, please enter a number above 2");
}
}
}

Categories