Fibonnaci sequence explanation - java

Can someone explain to me some parts of this code:
public static void sequence(int nterms){
int num1 = 0;
int num2 = 1;
int num = 2;
if (nterms <= 0){
System.out.println("Enter a positive integer");
}
else if (nterms == 1){
System.out.println(" fibonacci sequence: " + num1);
}
else{
System.out.println(num1 );
System.out.println(num2);
while (num < nterms){
int nth = num1 + num2;
System.out.println(nth);
num1 = num2;
num2 = nth;
num++;
}
}
}
The number sequence that's in the output is correct. So the code works. But why do you do num++ in the end? I know nth is previous two numbers added together but why do you nterms == 1 and print "" +num1? I don't get that.

Here it is
public static void sequence(int nterms){
/*instancation of needed variables : nth = num1+numb2 later in the code*/
int num1 = 0;
int num2 = 1;
/*num is the number of term you've encoutered, as the first two are in
the initialization, you start at 2*/
int num = 2;
if (nterms <= 0){ //check wether the function has a correct input or not*/
System.out.println("Enter a positive integer");
}
else if (nterms == 1){ /*if it's the first term we know in num1*/
System.out.println(" fibonacci sequence: " + num1);
}
else{
System.out.println(num1);/*we print the first two terms*/
System.out.println(num2);
while (num < nterms){ /*we loop till we reached the wanted number*/
/*we know a term is equal to the two terms before it, at least I hope you do*/
int nth = num1 + num2;
System.out.println(nth); /*we've got our number so we print it*/
num1 = num2; /*we make sure num1 and num2 are the last two encountered, so num1 becomre num2 and num2 become the current term (nth)*/
num2 = nth;
num++;/*we increment the variable as we've met printed a new term*/
}
}
}

Related

Why does my for loop return only half the elements I expect it to?

I would like to receive user input on n elements for the Fibonacci sequence. The scanner and calculations themselves seem to be working fine -- the input is successfully grabbed and the sequence calculated. It's even able to correctly disqualify inputs of a negative value. However, it is not actually returning 'n' elements. Curiously, I noticed that the loop consistently returns exactly half the elements requested, albeit in the correct order. If n = 20, the first 10 numbers are returned.
Here's the code:
public class fibonacci_input {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner myObj = new Scanner(System.in);
int num1 = 0;
int num2 = 1;
int n;
System.out.println("How many elements would you like in your Fibonacci sequence?");
n = myObj.nextInt();
if (n < 0)
System.out.println("Positive numbers only!");
else
System.out.println("Your Fibonacci sequence with " + n + " elements is:");
{ for (int i = 1; i <= n; ++i)
{
System.out.print(num1 + " ");
int num3 = num1 + num2;
num1 = num2;
num2 = num3;
++i;
}
}
}
}
I'm struggling to imagine what the problem could be. I first thought it might be a problem with the test condition statement, but similar (working) solutions online seem to have their loops formatted almost identically. Is it perhaps a problem with my variable declarations? I've tried multiple changes to no avail so would appreciate another set of eyes :)
You could just delete the second i++; statement in your code, this one is making the for loop run half times as expected, since the i variable is being incremented twice on each iteration
public class fibonacci_input {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
int num1 = 0;
int num2 = 1;
int n;
System.out.println("How many elements would you like in your Fibonacci sequence?");
n = myObj.nextInt();
if (n < 0)
System.out.println("Positive numbers only!");
else
System.out.println("Your Fibonacci sequence with " + n + " elements is:");
{ for (int i = 1; i <= n; ++i)
{
System.out.print(num1 + " ");
int num3 = num1 + num2;
num1 = num2;
num2 = num3;
//++i;
}
}
}
}

Code in Java to add two numbers is printing out sum backwards?

The following Java program (prints out addition problem of two given numbers) is printing the answer backwards ( for example, 563 instead of 365). How would I modify it so that it prints out the correct answer?
Note: I know that Im completing this problem in an unnecessarily complicated manner, but this is because we are only allowed to use primitive data types.
Thankyou.
//getting the number from user
Scanner linput = new Scanner(System.in);
System.out.print("Enter the first number:");
num = linput.nextInt();
System.out.println ("Enter the second number:");
num2 = linput.nextInt();
System.out.println (num);
System.out.println ("+");
System.out.println(num2);
System.out.println ("=======");
//making a copy of the input number
temp = num;
temp2 = num2;
//counting digits in the input number
while(num > 0)
{
num = num / 10;
count++;
}
while(num2 > 0)
{
num2 = num2 / 10;
count2++;
}
int answer = 0;
while(temp > 0 && temp2>0)
{
digit = temp % 10;
temp = temp / 10;
count--;
digit2 = temp2 % 10;
temp2 = temp2 / 10;
count2--;
answer = digit+digit2;
System.out.print(answer);
}
You problem statement is very unclear. If it's just simple addition of two numbers then you've really overcomplicated your implementation.
Scanner input = new Scanner(System.in);
System.out.print("Enter the first number:");
int num = input.nextInt();
System.out.print("Enter the second number:");
int num2 = input.nextInt();
System.out.print(num + " + " + num2 + " = " + (num + num2));
I totally agree with all comments that this is over complicated to do a sum. But the answer to the initial question why the result is printed backwards is that that you calculate the sum from right to left (units, tens, hundreds, ...) but print them left to right (default behavior of print)

While Loop - Sum of even numbers between two inclusive integers

EDIT: Lol I would've never thought you guys would be such savages. I thought this would be the right place for a college student to come and seek for answers. If I didn't care, why would I even be here.. Basically my question is different from the other ones because I do need the first loop to state my even numbers ie: 10 12 14 16 18 20. I sincerely hoped I would get some feedback on how to reinstate the original value of firstNum for the second loop, not criticism expecting to get selected as an answer for points in a matter of seconds.
I've implemented a code that I saw as an answer in a very similar question on the forum. Yet when I compile it, the output for my sum code doesn't return anything. It's just blank. Can I get some feedback on what I am missing or doing wrong? Thank you. BTW I can only use while loop.
System.out.println("Enter an integer:");
int firstNum = keyboard.nextInt();
System.out.println("Enter another integer larger than the first one:");
int secondNum = keyboard.nextInt();
System.out.println();
int mod = firstNum % 2;
int sum = 0;
if (mod != 0)
{
firstNum++;
}
System.out.print("Even numbers: ");
while (firstNum <= secondNum)
{
System.out.print(firstNum + " ");
firstNum += 2;
}
System.out.println();
System.out.print("Sum of even numbers: ");
while (firstNum <= secondNum)
{
System.out.print(sum);
sum += firstNum;
firstNum += 2;
}
The first loop only prints the even numbers, it can not add because the firstNum reaches the secondNum.
If you want to keep the same code you have, you only need to add a new variable that prints even numbers. So the first loop will print the even numbers and the second loop will do the sum.
For example:
int evenNumber;
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer:");
int firstNum = keyboard.nextInt();
System.out.println("Enter another integer larger than the first one:");
int secondNum = keyboard.nextInt();
System.out.println();
int mod = firstNum % 2;
int sum = 0;
if (mod != 0) {
firstNum++;
}
evenNumber = firstNum;
System.out.print("Even numbers: ");
while (evenNumber <= secondNum) {
System.out.print(evenNumber + " ");
evenNumber += 2;
}
System.out.println();
System.out.print("Sum of even numbers: ");
while (firstNum <= secondNum) {
sum += firstNum;
firstNum += 2;
}
System.out.println(sum);
This code is not optimal, but it complies with what you need. But if you want to do better, you can do it like this:
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer:");
int firstNum = keyboard.nextInt();
System.out.println("Enter another integer larger than the first one:");
int secondNum = keyboard.nextInt();
int total = 0;
System.out.print("Even Numbers: ");
while (firstNum <= secondNum) {
if (firstNum % 2 == 0) {
System.out.print(firstNum + " ");
total += firstNum;
}
firstNum++;
}
System.out.println("\nSum: " + total);
During your first while, you already changed the value of firstNum. So basically, when you arrive to the second while, you don't even enter it.
I would simply change the first loop and delete the second one :
while (firstNum <= secondNum) {
System.out.print(firstNum + " ");
sum += firstNum;
firstNum += 2;
}
System.out.println();
System.out.print("Sum of even numbers: ");
System.out.println(sum);
In your first while loop -
while (firstNum <= secondNum){
System.out.print(firstNum + " ");
firstNum += 2;
}
you keep incrementing variable firstNum until you reach secondNum, so the condition of the second while loop (firstNum <= secondNum) will never evaluates to true.
A very simple way to achieve your goal can be as follows.
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter an integer:");
int firstNum = keyboard.nextInt();
System.out.println("Enter another integer larger than the first one:");
int secondNum = keyboard.nextInt();
int total = 0;
while(firstNum <= secondNum){
if(firstNum%2 == 0)
total += firstNum;
firstNum++;
}
System.out.println("Sum: " + total);

How to print multiples of a given variable in java?

There are 3 numbers that are given to the user. These three numbers define the multiple, and the range. For example if these three numbers are (3, 6 , 17) the program should print 6,9,12,15. The first number is the base multiple and the second and third numbers are the lowest and the highest numbers (the range). I also know that I do not need all the import statements that I have.
This is what I have so far but I'm not sure how to continue.
import java.util.*;
import java.io.*;
import java.text.*;
import java.lang.Math.*;
public class printMultiplesOf{
public static void main (String [] args){
Scanner reader = new Scanner(System.in);
int num1, num2, num3;
System.out.println("Enter the 1st number");
num1 = reader.nextInt();
System.out.println("Enter the 2nd number");
num2 = reader.nextInt();
System.out.println("Enter the 3rd number");
num3 = reader.nextInt();
printMultiplesOf(num1, num2, num3);
}
public static void printMultiplesOf(int num1, int num2, int num3){
int start = num2
int end = num3
for (int i = num1; i <= num1; i++){
System.out.println(i + " ");
}
}
}
The main issue here is finding the loop's start and end point. The start point needs to the first number divisible by num1 equal or larger than num2. You can find it by dividing num2/num1 using floating-point division, ceil the result and multiply it back by num1. Similarly, the loop's end point should be the largest number divisible by num1 which is less than or equal to num3. You can find it by dividing num3/num1 using integer division (which would effectively floor the result and then multiplying it back again by num1. From there on, it's just a matter of looping in steps the size of num1. E.g.:
public static void printMultiplesOf(int num1, int num2, int num3) {
int start = ((int) Math.ceil((double) num2 / num1)) * num1;
int end = (num3 / num1) * num1;
for (int i = start; i <= end; i+= num1) {
System.out.println (i + " ");
}
}
Loop through all the numbers in the range, and check if it's a multiple.
public static void printMultiplesOf(int num1, int num2, int num3) {
for(int i=num2; i<= num3; i++){
if(i % num1 == 0)
System.out.print(i +" ");
}
}
This is your function. You simply add your num1 to i each time loop is executed.
I tried it and it is working ;)
public static void printMultiplesOf(int num1, int num2, int num3){
int multi = num1;
int start = num2;
int end = num3;
for (int i = start; i <= end; i += multi){
System.out.println(i + " ");
}
}

Not getting the output to my program, just says "running..."

I know the sumOfMultiples method itself works and that the problem lies in the main method. When I run it, nothing happens and it just continuously runs. I'm using netbeans if that makes a difference.
package examp;
public class Main {
public static void main(String[] args) {
Main example = new Main();
System.out.println("The answer is " + example.sumOfMultiples(2, 3));
}
public int sumOfMultiples(int num1, int num2) {
int num1Total = 0;
int num2Total = 0;
//Total of the multiples of the first number.
while (num1 < 1000) {
num1Total = num1Total + num1;
num1 = num1 + num1;
}
//Total of the multiples of the second number.
while (num2 < 1000) {
if (num2 % num1 != 0) { //Makes sure it doesn't add multiples of the first number twice.
num2Total = num2Total + num2;
}
}
return num1Total + num2Total;
}
}
Sorry if it's a stupid question, just made an account a couple of minutes ago.
Your second while loop doesn't increment num2 (that is why it doesn't stop)
while (num2 < 1000) {
if (num2 % num1 != 0) {
num2Total = num2Total + num2;
}
num2++; // <-- like so.
// or, num2 = num2 + 1;
}
Its in infinite while loop:
while (num2 < 1000) {
if (num2 % num1 != 0) { //Makes sure it doesn't add multiples of the first number twice.
num2Total = num2Total + num2;
}
}
If you want to debug on your own then run this (I have added couple of System.out.println statements) and you will know how:
public int sumOfMultiples(int num1, int num2) {
int num1Total = 0;
int num2Total = 0;
//Total of the multiples of the first number.
while (num1 < 1000) {
num1Total = num1Total + num1;
num1 = num1 + num1;
System.out.println("num1"+num1);
}
//Total of the multiples of the second number.
System.out.println("num1:"+num1+" "+"num2:"+num2);
while (num2 < 1000) {
if (num2 % num1 != 0) { //Makes sure it doesn't add multiples of the first number twice.
num2Total = num2Total + num2;
}
}
return num1Total + num2Total;
}
With this you get num1=1024 num2=3 and you can see that it will never go in the if loop so second while loop goes in infinite loop. Once it enters second while loop then num2 remains constant so you need to add some incrementer like num2++ which may allow it to come back after finite loops.

Categories