QuestionAsk Questions?

the recursive function gives a stack overflow error. I want to calculate the GDC ie the greatest Integer function for two input numbers. the code of my program is as follows and the error comes in the function gcd_func in the last condition giving stack overflow null. .I do not wish to use the scanner class Is there anything i can do to improve thiscode?

import java.io.*; public class reursion { public void main()throws IOException {BufferedReader stdin= new BufferedReader (new InputStreamReader( System.in)); System.out.println("Input two nos"); int a =Integer.parseInt(stdin.readLine()); int b =Integer.parseInt(stdin.readLine()); int gcd=1; int i=2; int p= gcd_func(a,b,gcd,i); System.out.println( "GCD+ +"+p); } int gcd_func(int a, int b, int gcd, int i) { if((a==1)||(b==1)) { return(gcd); } else if((a%i==0)&&(b%i==0)) { gcd=gcd*i; a=a/i; b=b/i; i++; return( gcd_func(a,b,gcd,i)); } else

{ i++; return( gcd_func(a, b, gcd, i)); } } }

View Answers

July 28, 2011 at 10:15 AM

import java.util.*; class FINDGCD{ public static int determineGCD(int a, int b) { if(b==0) return a; else return determineGCD(b, a % b); } public static void main(String[] args)throws Exception { FINDGCD cal = new FINDGCD(); Scanner input=new Scanner(System.in); System.out.println("Enter first number: "); int num1=input.nextInt(); System.out.println("Enter second number: "); int num2=input.nextInt(); int hcf = cal.determineGCD(num1, num2); System.out.println("GCD of two numbers= "+hcf); } }

Related Tutorials/Questions & Answers:

Advertisements