printing fibonacci number series without using loops - java

Is there a hack to print the first n fibonacci numbers without calling a loop
for(int i=1; i<n; i++)
System.out.println(computeF(n));
from the main program?
public static int computeF(int n)
{
if(n==0)
{
return 0;
}
else if(n==1)
{
return 1;
}
else
{
return computeF(n-1)+computeF(n-2);
}
}
There might be a way to print the intermediate values in recursion which will print the fibonacci numbers.

You could use tail recursion.

public class Fid
{
static int n1=0;
static int n2=1;
static int nex=0;
public static void fb(int n)
{
if(n<10)
{
if(n==0)
{
System.out.print(" "+n);
n++;
fb(n);
}
else
if(n==1)
{
System.out.print(" "+n);
n++;
fb(n);
}
else{
nex=n1+n2;
System.out.print(" "+nex);
n1=n2;
n2=nex;
n++;
fb(n);
}
}
}
public static void main(String[] args)
{
fb(0);
}
}

using recursion:-
class FibonacciRecursion
{
private static int index = 0;
private static int stoppingPoint = 9;
public static void main (String[] args)
{
int n1 = 0;
int n2 = 1;
fibonacciSequence(n1, n2);
}
public static void fibonacciSequence(int n1, int n2)
{
System.out.println("index: " + index + " -> " + n1);
// make sure we have set an ending point so this Java recursion
// doesn't go on forever.
if (index == stoppingPoint)
return;
// make sure we increment our index so we make progress
// toward the end.
index++;
fibonacciSequence(n2, n1+n2);
}
}

//Java program to print Fibonacci Series up to n terms given by user without using loop
import java.util.* ;
public class Fibonacci
{
public static void main(String[] arguments)
{
Scanner s = new Scanner(System.in);
System.out.print("Enter the no of terms :");
int no_of_terms= s.nextInt(),a=1,b=0,c=0,count=1;
System.out.print("0 ");//printing the first term
fib(no_of_terms,a,b,c,count);}
public static void fib(int no_of_terms,int a,int b,int c,int count)
{
//when value of count will be equal to the no of terms given by user the program will terminate
if (count==no_of_terms)
System.exit(0);
else
{
count++;
System.out.print(a+" ");
c=b;
b=a;
a=b+c;//calculating the next term
fib(no_of_terms,a,b,c,count);//calling the function again with updated value
}
}
}

import java.util.*;
public class Fibonacci{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a no.");
int n= sc.nextInt(),a=1,b=0,c=0;
num(n,a,b,c);
}
public static void num(int n,int a,int b,int c){
if(a<=n){
System.out.println(a);
c=b;
b=a;
a=b+c;
num(n,a,b,c);
}
}
}

Related

Function value always getting multiplied by 2

I have created a function "m7" in my class but this function is always returning value getting multiplied by 2.
If I am running this function in "psvm" it is printing the right value.
In my Alice class, the method m7() is returning 10 which is incorrect but if I am running this method in psvm then it is returning 5 which is correct.
package com.math.functions;
import java.util.*;
public class Alice {
Integer[] rank= new Integer[7];
Integer n=65;
int count=0;
public Alice() {
rank[0]=100;
rank[1]=100;
rank[2]=90;
rank[3]=80;
rank[4]=75;
rank[5]=60;
rank[6]=n;
//rank[6]=20;
//rank[7]=10;
//rank[8]=n;
Arrays.sort(rank, Collections.reverseOrder());
}
public void print() {
for (Integer a : rank) {
System.out.println(a);
}
}
public int m7() {
for (int i = 0; i < rank.length; i++) {
if (rank[i] == n) {
break;
}
count++;
}
return count;
}
public void res(){
int s = m7();
System.out.println("this is the value of s here :"+s);
Set<Integer> hash_Set = new HashSet<>();
for(int i=0;i<=s/2;i++){
System.out.println("hii");
hash_Set.add(rank[i]);
}
for(Integer o:hash_Set){
System.out.println(o);
System.out.println("rank:"+hash_Set.size());
}
}
public static void main(String[] args) {
Alice a=new Alice();
a.print();
System.out.println("this is: "+a.m7());
a.res();
}
}
You are reusing the value of count from the previous time you run it.
Don't declare count as a member variable, make it a local variable.
public int m7() {
int count = 0; // HERE
for (int i = 0; i < rank.length; i++) {
if (rank[i] == n) {
break;
}
count++;
}
return count;
}

How do i call "recall" method?

Please tell me how to call recall method.
I am new in Java.
I am making a program to display prime and composite number.
package composite;
import java.util.Scanner;
public class composite {
public static void main(String[] args) {
Scanner p = new Scanner(System.in);
System.out.println("press number till you want composite number & prime numbers");
int m=p.nextInt();int g[]=new int [m+1];prime(m);
for(int k=4;k<=m;k++)
{
for(int b=2;b<k;b++){
if(k%b==0){
g[k]=k;break;
}
}
}
}
public static int prime(int m){
int e[]= new int[m+1];
for(int i=2;i<m;i++)
{
int p=0;
for(int j=2;j<i;j++)
{
if(i%j==0)
p=1;
}
if(p==0)
e[i]=i;
}return(m);
}
public static int recall(int m, int [] e, int [] g){
for(int a=1;a<m;a++){
System.out.println(e[a]+" "+g[a]);
}
return m;
}
}
Take a look at following and modify the variables accordingly :
Composite call_recall = new Composite();
int recall_value = recall(m,e,g);
Place the proper values as you require in place of m, e and g.

How to find the largest integer (n), such that n^3 < 12,000, using a while loop

This is what I have so far. The idea is it's supposed to increase n until n^3 is less than 12000, and print out n at the highest integer below 12k.
public static void main(String[] args) {
int n = 0;
int nCubed = (int) (Math.pow(n, 3));
while (nCubed < 12000) {
n++;
}
System.out.println("The highest integer below 12000 is " +n);
}
}
You need to set the nCubed value each time in the loop:
public static void main(String[] args) {
int n = 0;
int nCubed = (int) (Math.pow(n, 3));
while (nCubed < 12000) {
n++;
nCubed = (int) (Math.pow(n, 3));
}
System.out.println("The highest integer below 12000 is " +(n-1));
}
public class newClass{
public static void main(String[] args) {
int largestValue=0;
int n=0;
while(Math.pow(n,3)<12000) {
if(n>largestValue)
largestValue=n;
n++;
}
System.out.println(largestValue);
}
}
public class Loops_13
{
public static void main(String[] args)
{
int n = 0;
while (Math.pow(n,3) < 12000)
{
if (Math.pow(n + 1,3) >= 12000)
break;
n++;
}
System.out.println("The largest integer n such that n^3 is less than 12,000 is " + n);
}
}
//Find the largest n
public class Pb5 {
public static void main(String[] args) {
int n=0;
while(true) {
if(n*n*n<12000) {
n++;
}
else
break;
}
System.out.println("The largest integer n less than 12000 is:: "+(n-1));
}
}

Heap Sort. What's wrong in this code?

I am able to create a Max Heap using a function heapify() but when i try to call it again(to delete max and create a sorted array) the program gets stuck/doesn't stop taking input. What's wrong?
Is this a memory problem?If I increase the number of calls by increasing the frequency of for loop it still works fine.
public class HeapSort
{
int[] heap;
public void sort(int length)
{
int temp;
for(int i=length;i>=1;i--)
{
heapify(i,length);
}
//if I try to call heapify again(even once) after this,the program gets stuck
}
public void heapify(int i,int l)
{
int lchild=2*i,rchild,max;
int temp;
while(lchild<=l)
{
rchild=(2*i)+1;
if(rchild<=l)
max=(heap[lchild]>heap[rchild])? lchild:rchild;
else
max=lchild;
if(heap[i]<heap[max])
{
temp=heap[i];
heap[i]=heap[max];
heap[max]=temp;
i=max;
}
lchild=2*i;
}
}
public static void main(String args[]) throws IOException
{
BufferedReader r= new BufferedReader(new InputStreamReader(System.in));
int length=Integer.parseInt(r.readLine());
HeapSort Heap=new HeapSort();
Heap.heap=new int[length+1];
for(int i=1;i<=length;i++)
Heap.heap[i]=Integer.parseInt(r.readLine());
Heap.sort(length);
for(int i=1;i<=length;i++)
System.out.print(Heap.heap[i]+" ");
}
}
Heapify should be done for length/2 iterations because it is like a tree structure.
Here is a complete code for heap sort...This sort array 's'
public class HeapSort {
public static void main(String[] args) {
String s[]={"aaaa","dddd","cccc","gggg","bbbbb"};
AsHeap(s);
HeapSort(s);
for(String x:s){
System.out.println(x);
}
}
public static void AsHeap(String s[]){
for( int i = s.length / 2; i >= 0; i-- ){
DownHeap( s, i, s.length );
}
}
public static void HeapSort(String[] s){
for(int i=s.length-1;i>0;i--){
swap(s,0,i);
DownHeap(s,0,i);
}
}
public static int getLeftChildIndex(int i){
return 2 * i + 1;
}
private static void DownHeap(String[] s, int i, int length) {
int indexOfChild;
String temp;
for(temp=s[i];getLeftChildIndex(i)<length;i=indexOfChild){
indexOfChild=getLeftChildIndex(i);
if(indexOfChild !=length-1 && s[indexOfChild].compareTo(s[indexOfChild+1])<0){
indexOfChild++;
}
if(temp.compareTo(s[indexOfChild])<0){
s[i] = s[indexOfChild];
} else{
break;
}
}
s[i] = temp;
}
public static void swap(String s[],int x,int y){
String temp=s[x];
s[x]=s[y];
s[y]=temp;
}
}
The while loop isn't terminating when there is no swap between the parent and the child(i.e. the parent is greater than the child).
The value of i(just above main method) doesn't change when parent is greater. Simply taking the line i=max outside the if block [if(heap[i]
Also,is there any sequence to learn Algorithms?If so,kindly guide me.
Thank you.

Write a program to accept number from command line and display sum of digits in a number by using recursive funcion

I have written the code but it displays Stackoverflowerror message.
class Sum
{
int ans=0,temp,temp2;
int getsum(int no)
{
if(no>0)
{
temp=no % 10;
ans=ans + temp;
getsum(no/10);
}
else
{
return ans;
}
}
}
class recsum
{
public static void main(String args[])
{
Sum s=new Sum();
int no,len;
len=args.length;
if(len==0)
{
System.out.println("No argruments are given ! ");
}
else
{
no=Integer.valueOf(args[0]).intValue();
System.out.println("Sum of digits= " + s.getsum(no));
}
}
}
You are over-complicating things a lot in your code. Here is a simpler working example:
public static int getSum(final String[] args, final int index) {
if (index < args.length) {
return Integer.valueOf(args[index]) + getSum(args, index + 1);
} else {
return 0;
}
}
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("You need to provide numbers as arguments.");
}
final int sum = getSum(args, 0);
System.out.println("Sum: " + sum);
}
You are supposed to be recursive, this is in the getSum function, because it is calling itself with differing parameters.
In recursive functions, you always need to have an exit branch that causes the calling to stop.
As sums won't change if you add 0 this can be exploited for a very clean exit.
The Stack overflow is normally because you never bottom out of the recursion.
Change class Sum to this:
class Sum {
int ans = 0, temp = 0;
int getsum(int no) {
if((no/10)-.5 >= 1)
ans += getsum(no/10);
else
return ans;
}
}
I'm not completely sure if this will work, and I can't compile it right now. I think this is one way to do it, but again, I'm not completely sure.
Program: Write a program to use Command Line Arguments.
class Sumnum1
{
int i,t,num,sum=0;
void getData(String s)
{
num=Integer.parseInt(s);
}
int digitSum()
{
for(i=num;i>=1;i=i/10)
{
t=i%10;
sum=sum+t;
}
return sum;
}
public static void main(String arg[])
{
int ds=0;
Sumnum1 obj=new Sumnum1();
obj.getData(arg[0]);
ds=obj.digitSum();
System.out.println("sum of digit="+ds);
}
}
BY :ANKIT AGRAWAL (A.A.)

Categories

Resources