I'm a absolutly beginner in java and i want to write a code with the acm.libary, which is about the fibonacci sequence.
The result is very nice for me, but i want only print the last number of the sequence. I don't know how.
If the user type n = 5, the result need to be 8.
If the user type n = 8, the result need to be 21.
In my program it is the last number, but the program also prints all the previous numbers.
I hope you can understand me :D
Thank you in advance!
int a = 1;
int b = 0;
public void run() {
int n = readInt ("n: ");
for(int i = 1; i <= n; i++) {
println (fibonacci (n));
}
}
private int fibonacci(int n) {
int c = (a) + (b);
a = b;
b = c;
return c;
}
Try this code.
import java.util.Scanner;
public class Test {
int a = 1;
int b = 0;
public int run() {
#SuppressWarnings("resource")
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int value =0;
for(int i = 1; i <= n; i++) {
value = fibonacci (n);
}
return value;
}
private int fibonacci(int n) {
int c = (a) + (b);
a = b;
b = c;
return c;
}
public static void main (String arg[])
{
Test t = new Test();
System.out.println(t.run());
}
}
You can replace the body of the loop by this:
if (i == n) {
println (fibonacci (n));
} else {
fibonacci (n);
}
Related
This is my code so far but I am having trouble. I tried to create an array with all the prime
factors and print the last index of the array but I having trouble figuring out the length the array should be. Am I doing this all wrong? Is there a better method?(New to stack overflow)(still learning java).
import java.util.*;
public class Main
{
public static void main(String [] args)
{
Scanner sc = new Scanner(System.in);
int num = sc.nextInt(); //Given Number
sc.close();
int n = 0;
int [] PrimeFactors = new int[num];
for(int i = 1; n < PrimeFactors.length; i++)
{
if(checkPrime(i) == false && num % i == 0)
{
PrimeFactors[n] = i;
n++;
}
}
System.out.println(PrimeFactors[PrimeFactors.length - 1]);
}
public static boolean checkPrime(int a)
{
boolean bool = false;
if(true)
{
for(int i = 2; i <= a / 2; i++)
{
if(a % i == 0)
{
bool = true;break;
}
}
}
return bool;
}
}
I have made this program using array concept in java. I am getting Exception as ArrayIndexOutOfBound while trying to generate product.
I made the function generateFNos(int max) to generate factors of the given number. For example a number 6 will have factors 1,2,3,6. Now,i tried to combine the first and the last digit so that the product becomes equal to 6.
I have not used the logic of finding the smallest number in that array right now. I will do it later.
Question is Why i am getting Exception as ArrayIndexOutOfBound? [i couldn't figure out]
Below is my code
public class SmallestNoProduct {
public static void generateFNos(int max) {
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
}
}
smallestNoProduct(ar);
}
public static void smallestNoProduct(int x[]) {
int j[] = new int[x.length];
int p = x.length;
for (int d = 0; d < p / 2;) {
String t = x[d++] + "" + x[p--];
int i = Integer.parseInt(t);
j[d] = i;
}
for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}
}
public static void main(String s[]) {
generateFNos(6);
}
}
****OutputShown****
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
at SmallestNoProduct.smallestNoProduct(SmallestNoProduct.java:36)
at SmallestNoProduct.generateFNos(SmallestNoProduct.java:27)
at SmallestNoProduct.main(SmallestNoProduct.java:52)
#Edit
The improved Code using array only.
public class SmallestNoProduct {
public static void generateFNos(int max) {
int s = 0;
int ar[] = new int[max];
int k = 0;
for (int i = 1; i <= max; i++) {
if (max % i == 0) {
ar[k] = i;
k++;
s++;
}
}
for (int g = 0; g < s; g++) {
System.out.println(ar[g]);
}
smallestNoProduct(ar, s);
}
public static void smallestNoProduct(int x[], int s) {
int j[] = new int[x.length];
int p = s - 1;
for (int d = 0; d < p;) {
String t = x[d++] + "" + x[p--];
System.out.println(t);
int i = Integer.parseInt(t);
j[d] = i;
}
/*for (int u = 0; u < j.length; u++) {
System.out.println(j[u]);
}*/
}
public static void main(String s[]) {
generateFNos(6);
}
}
Maybe it better:
public class SmallestNoProduct {
public static int smallest(int n) {
int small = n*n;
for(int i = 1; i < Math.sqrt(n); i++) {
if(n%i == 0) {
int temp = Integer.parseInt(""+i+""+n/i);
int temp2 = Integer.parseInt(""+n/i+""+i);
temp = temp2 < temp? temp2: temp;
if(temp < small) {
small = temp;
}
}
}
return small;
}
public static void main(String[] args) {
System.out.println(smallest(6)); //6
System.out.println(smallest(10)); //25
System.out.println(smallest(100)); //205
}
}
Problem lies in this line
String t=x[d++]+""+x[p--];
x[p--] will try to fetch 7th position value, as p is length of array x i.e. 6 which results in ArrayIndexOutOfBound exception. Array index starts from 0, so max position is 5 and not 6.
You can refer this question regarding postfix expression.
Note: I haven't checked your logic, this answer is only to point out the cause of exception.
We are unnecessarily using array here...
below method should work....
public int getSmallerMultiplier(int n)
{
if(n >0 && n <10) // if n is 6
return (1*10+n); // it will be always (1*10+6) - we cannot find smallest number than this
else
{
int number =10;
while(true)
{
//loop throuogh the digits of n and check for their multiplication
number++;
}
}
}
int num = n;
for(i=9;i>1;i--)
{
while(n%d==0)
{
n=n/d;
arr[i++] = d;
}
}
if(num<=9)
arr[i++] = 1;
//printing array in reverse order;
for(j=i-1;j>=0;j--)
system.out.println(arr[j]);
I tried making a Java program executing the Fibonacci sequence.
Here's my code:
import java.io.*;
public class Fibonacci{
public static void main(String[]args){
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
int ctr1=0;
int ctr2=0;
int num1=0;
int num2=0;
int num3=0;
try{
System.out.println("How many numbers would you want to see?");
ctr2=Integer.parseInt(Data.readLine());
for(int ans=0; ctr1==ctr2; ctr1++){
num1++;
System.out.println(num2 + "\n" + num1);
ans=num1+num2;
System.out.println(ans);
ans=num3;
}
}catch(IOException err){
System.out.println("Error!" + err);
}catch(NumberFormatException err){
System.out.println("Invald Input!");
}
}
}
Obviously, I'm a beginner in Java and I don't know how to properly use the for statement. Would somebody be kind enough to make my code work? Or maybe make a way shorter code that works. I'm a beginner so be cool. Thanks :)
Fibonacci series in java is actually quite simple and can be done with just one single for-loop!!!!
import java.io.*;
class fibonacci{
public static void main() throws NumberFormatException, IOException{
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
int a,b,c,d;
System.out.println("Upto How many numbers do you want to see?");
d=Integer.parseInt(Data.readLine());
for (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){
System.out.println(a);
}
}
}
This has been done using buffered reader........ If you are said to use only bufferedreader go for this else you can use Scanner class which is much simple and easy to use because you don't have to catch or throw any exceptions.....
Scanner program:-
import java.util.*;
class fibonacci{
public static void main(){
Scanner sc = new Scanner(System.in);
int a,b,c;
System.out.println("Upto How many numbers do you want to see?");
d=sc.nextInt();
for (a=0,b=1,c=a;a<d;c=a,a+=b,b=c){
System.out.println(a);
}
}
}
Now as I said in one loop you can do it.... Here is another method where you do the swapping inside the body of the loop and not in the arguments of it...
And this is much simplier to understand for beginners as u don't have to pass multiple variables inside the arguments and yeah its a bit longer
import java.util.*;
class fibonacci{
public static void main(){
Scanner sc = new Scanner(System.in);
int a = 0,b = 1,c,d;
System.out.println("Upto How many numbers do you want to see?");
d=sc.nextInt();
System.out.println(a +"\n" +b);//\n is used to go to next line....
for (c=0;c<d;c++){
c = a + b;//Doing and printing the fibonacci...
System.out.println(c);
a = b;
b = c;//Swapping the values...
}
}
}
So here i have given you three methods that should give the same output(Most probably) choose whichever is convenient for you..
Look at this code snippet which is much easier than yours to understand. Solution tip is simple, you keep 2 pointers for the first 2 fibonacci numbers and update them appropriately in the loop. In the example below, the loop executes 10 times, you can modify it as desired.
static void fibonacci() {
int ptr1 = 1, ptr2 = 1;
int temp = 0;
System.out.print(ptr1 + " " + ptr2 + " ");
for (int i = 0; i < 10; i++) {
System.out.print(ptr1 + ptr2 + " ");
temp = ptr1;
ptr1 = ptr2;
ptr2 = temp + ptr2;
}
}
Output:
1 1 2 3 5 8 13 21 34 55 89 144
Expanding on the answers, if you want to look really cool use recursion.
public class Fibonacci {
public static long fib(int n) {
if (n <= 1) return n;
else return fib(n-1) + fib(n-2);
}
public static void main(String[] args) {
int N = 300; // how many numbers you want to generate
for (int i = 1; i <= N; i++)
System.out.println(i + ": " + fib(i));
}
}
Here is Google search of what it is, hope those resources help: http://bit.ly/1cWxhUS
I'm a beginner in java as well however I've found an easy way to create a Fibonacci number using an array. The basic principle of a Fibonacci number is the addition of the current number and the number that came before.
Here is my code:
//Creation of array
int [ ] fib = new int[size];
//Assigning values to the first and second indexes of array named "fib"
fib [0] = 0;
fib [1] = 1;
//Creating variable "a" to use in for loop
int a = 1
//For loop which creates a Fibonacci number
for( int i = 2; i < size ; i++)
{
fib[i] = a;
a = fib[i] + fib[i-1];
}
This is another algorithm which I found online and I kind of simplified the code from it.
public static BigInteger fib(BigInteger x) {
if (x.intValue() < 0){return x.intValue() % 2 == 0 ?fib(x.multiply(BigInteger.valueOf(-1))).multiply(BigInteger.valueOf(-1)) : fib(x.multiply(BigInteger.valueOf(-1)));}
int n = Integer.valueOf(x.toString());
BigInteger a = BigInteger.ZERO,b = BigInteger.ONE;
for (int bit = Integer.highestOneBit(n); bit != 0; bit >>>= 1) {
BigInteger d = a.multiply(b.shiftLeft(1).subtract(a));
BigInteger e = a.multiply(a).add(b.multiply(b));
a = d;
b = e;
if ((n & bit) != 0) {
BigInteger c = a.add(b);
a = b;
b = c;
}
}
return a;
}
I know there is a chance that you wont understand how to use BigInteger, so I am giving you this link, just trying to be helpful.
Here we get Fibonacci Series up to n.
public static void fibSequence(int n) {
int sum = 0;
for (int x = 0, y = 1; sum < n; x = y, y = sum, sum = x + y) {
System.out.print(sum + " ");
}
}
Example:
Input: n = 20
Output: 0 1 1 2 3 5 8 13
more simple way
public static void main(String[] args) {
int first = 1;
int second = 2;
for (int i = 0; i < 20; i++) {
if (i == 0)
System.out.print(first);
System.out.print("," + second);
int temp = second;
second = first + second;
first = temp;
}
}```
program output :: 1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,10946
import java.util.*;
public class sequence1
{
public static void main(String[] args)
{
sequence1 fs=new sequence1();
fs.fibonacci();
}
public void fibonacci()
{
int numb1 = 1;
int numb2 = 1;
int temp = 0;
#SuppressWarnings("resource")
Scanner input=new Scanner(System.in);
System.out.println("How Many Terms? (Up To 45)");
int x=input.nextInt();
x=x-2;
System.out.println(numb1);
System.out.println(numb2);
for (int i = 0; i < x; i++)
{
System.out.println(numb1 + numb2 + " ");
temp = numb1;
numb1 = numb2;
numb2 = temp + numb2;
}
}
}
This function return the fibonacci series
/**
* #param startElement
* #param secondElent
* #param length :length of fibonacci series
* #return fibonacciseries : contain the series of fibonacci series
*/
public int[] createFibonacciSeries(int startElement, int secondElent,
int length) {
int fibonacciSeries[] = new int[length];
fibonacciSeries[0] = startElement;
fibonacciSeries[1] = secondElent;
for (int i = 2; i < length; i++) {
fibonacciSeries[i] = fibonacciSeries[i - 1]
+ fibonacciSeries[i - 2];
}
return fibonacciSeries;
}
import java.util.*;
class MyFibonacci {
public static void main(String a[]){
int febCount = 15;
int[] feb = new int[febCount];
feb[0] = 0;
feb[1] = 1;
for(int i=2; i < febCount; i++){
feb[i] = feb[i-1] + feb[i-2];
}
for(int i=0; i< febCount; i++){
System.out.print(feb[i] + " ");
}
}
}
public class FibonacciExercitiu {
public static void main(String[] args) {
int result = fib(6); //here we test the code. Scanner can be implemented.
System.out.println(result);
}
public static int fib(int n) {
int x = 1;
int y = 1;
int z = 1; //this line is only for declaring z as a variable. the real assignment for z is in the for loop.
for (int i = 0; i < n - 2; i++) {
z = x + y;
x = y;
y = z;
}
return z;
}
/*
1. F(0) = 1 (x)
2. F(1) = 1.(y) =>Becomes x for point4
3.(z)F(2) = 2 (z) =>Becomes Y for point4 // becomes X for point 5
4.(z)F(3) = 3 // becomes y for point 5
5.(z)F(4) = 5 ..and so on
*/
}
public static int[] fibonachiSeq(int n)
{
if (n < 0)
return null;
int[] F = new int[n+1];
F[0] = 0;
if (n == 0)
return F;
F[1] = 1;
for (int i = 2; i <= n; i++)
{
F[i] = F[i-1] + F[i-2];
}
return F;
}
Using while loop
class Feb
{
static void Main(string[] args)
{
int fn = 0;
int sn = 1;
int tn = 1;
Console.WriteLine(fn);
Console.WriteLine(sn);
while (true)
{
tn = fn + sn;
if (tn >10)
{
break;
}
Console.WriteLine(tn);
fn = sn;
sn = tn;
}
Console.Read();
}
}
public class Febonacci {
public static void main(String[] args) {
int first =0;
int secend =1;
System.out.print(first+","+secend);
for (int k=1;k<7;k++){
System.out.print(","+(first+secend ));
if(k%2!=0)
first+=secend;
else
secend+=first;
}
}
}
public class FibonacciSeries {
public static void main(String[] args) {
int a=0, c=0, b=1;
for(int i=0; i<10; i++) {
System.out.print(c+" ");
a = c + b;
c = b;
b = a;
}
}
}
I need help with this loop. One of my course assignments is to make a LCM program.
Sample output:
(8,12) LCM is 24
(4,3) LCM is 12
(5,10,20) LCM is 20
(18,24,52) LCM is 936
(12,10,26) LCM is 780
(99,63,24) LCM is 5544
(62,16,24) LCM is 1488
I have this so far for 2 numbers but I'm not sure how to do 3 numbers. We're supposed to use methods on other classes so this is what I have for the LCM class.
public class LCM {
private int n, x, s = 1, t = 1;
public LCM()
{
n = 0;
x = 0;
s = 1;
t = 1;
}
public int lcmFind(int i, int y) {
for (n = 1;; n++) {
s = i * n;
for (x = 1; t < s; x++) {
t = y * x;
}
if (s == t)
break;
}
return (s);
}
}
If you want to get LCM of 3+ numbers you can use your method lcmFind in following way:
int a = 2;
int b = 3;
int c = 5;
LCM l = new LCM();
int lcm = l.lcmFind(l.lcmFind(a, b), c);
Reccomendations:
Make n,x, s and t variables local in lcmFind. Because you need them ONLY in lcmFind method and you need to reset their values in every invocation of lcmFind.
Make your lcmFind method static. You don't need to instantiate new object in order to calc lcm. This way you can use it like LCM.lcmFind(3,4), or even better rename method and use something like LCM.find(3,4).
EDIT
If you need to make method that takes variable number of argument you should check varargs. So you'll get something like:
public int lcmFind(int.. args) {
// args is actually array of ints.
// calculate lcm of all values in array.
// usage: lcmFind(1,4) or lcmFind(1,5,6,3)
}
You can use your first version of lcmFind that takes 2 arguments and calculate lcm of many values using it.
EDIT 2
If you need only 2 and 3-args version of lcmFind than you can just add 3-arg version:
public int lcmFind(int a, int b, int c) {
return lcmFind(lcmFind(a, b), c);
}
I found this link and I guess this is most simple and clean solution:
/**
* Calculate Lowest Common Multiplier
*/
public static int LCM(int a, int b) {
return (a * b) / GCF(a, b);
}
/**
* Calculate Greatest Common Factor
*/
public static int GCF(int a, int b) {
if (b == 0) {
return a;
} else {
return (GCF(b, a % b));
}
}
try
public int lcm(int... a) {
for (int m = 1;; m++) {
int n = a.length;
for (int i : a) {
if (m % i != 0) {
break;
}
if (--n == 0) {
return m;
}
}
}
}
public static int gcd(int a, int b){
return (b == 0) ? a : gcd(b, a % b);
}
public static int gcd(int... args){
int r = args[0];
int i = 0;
while(i < args.length - 1)
r = gcd(r,args[++i]);
return r;
}
public static int lcm(int a, int b){
return a * b / gcd(a,b);
}
public static int lcm(int... args){
int r = args[0];
int i = 0;
while(i < args.length - 1)
r = lcm(r,args[++i]);
return r;
}
static int getLCM(int a,int b)
{
int x;
int y;
if(a<b)
{
x=a;
y=b;
}
else
{
x=b;
y=a;
}
int i=1;
while(true)
{
int x1=x*i;
int y1=y*i;
for(int j=1;j<=i;j++)
{
if(x1==y*j)
{
return x1;
}
}
i++;
}
}
I think you have the answer already, since it's an old post. still posting my answer. Below is the code to find the LCM for an array:
import java.util.Arrays;
import java.util.Scanner;
public class ArrayEqualAmz {
static int lcm =1;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int [] arr = new int[n];
for(int i=0; i<n; i++){
arr[i] = sc.nextInt();
}
System.out.println("lcm = "+lcm(arr));
}
// find the factor
public static int divisor(int x[]){
Arrays.sort(x);
int num=0;
for(int i=x.length-1; i>=0; i--){
if(x[i] != 1 )
num=x[i];
}
for(int j=2; j<=num; j++){
if(num%j==0){
return j;}
}
return num;
}
//finding the lcm
public static int lcm(int arr[]){
while(true){
int j = divisor(arr);
if(j==0){break;}
lcm = lcm*j;
for(int i=0; i<arr.length; i++){
if(arr[i]%j==0){
arr[i] = arr[i]/j;}
System.out.print(arr[i]+",");
}
System.out.println( " factor= "+lcm);
return lcm(arr);
}
return lcm;
}
}
Try this
int n1 = 72, n2 = 120, lcm;
// maximum number between n1 and n2 is stored in lcm
lcm = (n1 > n2) ? n1 : n2;
// Always true
while(true)
{
if( lcm % n1 == 0 && lcm % n2 == 0 )
{
System.out.printf("The LCM of %d and %d is %d.", n1, n2, lcm);
break;
}
++lcm;
}
You can re use the same function written for lcm of two numbers. Just pass one of the arguments as follows:
The function code can be like this:
public static int lcm(int num1,int num2) {
boolean flag = false;
int lcm = 0;
for(int i= 1;!flag; i++){
flag = (num1 < num2)?(num2*i)%num1==0:(num1*i)%num2==0;
lcm = num1<num2?num2*i:num1*i;
}
return lcm;
}
Call the function like this:
public static void main(String[] args) {
System.out.println("lcm "+lcm(lcm(20,80),40));
}
Basically, I would like to know if there is a shorter way of printing out the Fibonacci numbers from 0 - 100.
What I have done is probably very basic, but here is the code:
public static void main(String[] args) {
int number[] = new int[100];
number[0] = 0;
number[1] = 1;
int sum1 = number[0] + number[0];
int sum2 = sum1 + number[1];
int sum3 = sum1 + sum2;
int sum4 = sum2 + sum3;
int sum5 = sum3 + sum4;
int sum6 = sum4 + sum5;
System.out.println(sum1);
System.out.println(sum2);
System.out.println(sum3);
System.out.println(sum4);
System.out.println(sum5);
System.out.println(sum6);
}
And I would be doing this up until 100. But I'm sure there is a quicker way of doing this. How?
You can use a loop. This example uses BigInteger as the number quickly become too large for long.
BigInteger a = BigInteger.ZERO, b = BigInteger.ONE;
System.out.println(1);
for (int i = 0; i < 100000; i++) {
BigInteger c = a.add(b);
System.out.println(c);
a = b;
b = c;
}
prints after a couple of seconds finally
420269270299515438 ... many, many digits deleted ... 9669707537501
Note: you don't need to memorize all the previous values, just the last two.
Standard way to do this is by recursion:
Have a look at this simple snippet, which returns the fibonacci number at position a:
public static long fib(int a){
if (a==1||a==2) return 1;
else return fib(a-1)+fib(a-2);
}
google search ftw!... wasn't even a minute searching
int[] fibonacci = new int[25+1];
fibonacci[1] = 1;
fibonacci[2] = 1;
for ( int i = 3; i < fibonacci.length; i++ )
{
fibonacci[i] = fibonacci[i-2] + fibonacci[i-1];
}
Print number < 100 with n=11
public int getFib(int n){
if(n==0) return 0;
else if(n==1) return 1;
else{
int temp=getFib(n-1)+getFib(n-2);
return temp;
}
}
Just in case you don't want to use the recursive way..
Here is the iterative...
public class Fib2 {
public static int fib(int n, int a, int b)
{
if (n==0)
{
System.out.print("1x +");
return a;
}
else
{
System.out.print("2x +");
return fib(n-1,b,a+b);
}
}
public static void main(String arg[])
{
System.out.println(fib(0,1,1));
}
}
Well, 100 isn't one of the Fibonacci numbers, however if we include 144, then this is a nice succinct example:
class F
{
public static void main( final String[] a )
{
int a = 1, b = 1;
for ( ; b < 145; a = b + (b = a) )
System.out.println( b );
}
}
If you have to do this without arrays here is the way to do it. Just change 20 to 100. This is the way I had to do it for an assignment and it is simple to understand for those still learning.
public static void main(String[] args)
{
int number1 = 1;
int number2 = 1;
int count;
int fib;
System.out.print(number1 + " " + number2 + " ");
for(count = 3; count <= 20; count++)
{
fib = number1 + number2;
number1 = number2;
number2 = fib;
System.out.print(fib + " ");
}
}