954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

GCD Nonrecursive Beginner

hey guys I'm a newb to this C++ programming and I need help. I've made a non-recursive GCD C++ code, but i was having problems with the algorithm. Can someone help please?

import java.util.Scanner;
public class GCD
{
public static int GCD;
public static int div;
public static int remainder = 1;

public static void main(String [] args)
{
int num2;

Scanner keyboard = new Scanner(System.in);
do{
//Prompting for first number
System.out.println("Enter the first number: ");
int num1 = keyboard.nextInt();

//Exit
if(num1 <= 0)
{
System.exit(0);
}//Ending of if

//Prompting for second number
System.out.println("Enter the second number: ");
num2 = keyboard.nextInt();

div = num1 / num2;
remainder = num1 % num2;

if (num1 < num2)
{
div = num1;
num1 = num2;
num2 = div;
}

while(remainder != 0)
{
div = num1 / num2;
remainder = num1 % num2;
num1 = num2;
num2 = remainder;
}
num2 = GCD;

System.out.println("The GCD is: " + GCD);
} while (GCD >= 0);


}//Ending bracket of method main
}//Ending bracket of class

ronak127
Newbie Poster
2 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

I say you need help, this is Java.

gerard4143
Nearly a Posting Maven
2,272 posts since Jan 2008
Reputation Points: 512
Solved Threads: 387
 

excuse me it was suppose to say Java.. sorry i had someone else put this thread up for me

ronak127
Newbie Poster
2 posts since Oct 2011
Reputation Points: 10
Solved Threads: 0
 
div = num1 / num2;    
            remainder = num1 % num2;

1)Let num1 = 6 and num2 = 3. Then div = 6/3 = 2. and the remainder 6%3 = 0.
2)
if (num1 < num2)
{
div = num1;
num1 = num2;
num2 = div;
}

This is irrelevant in the above case since num1 > num2. So its skipped.

3)
while(remainder != 0)
{
div = num1 / num2;
remainder = num1 % num2;
num1 = num2;
num2 = remainder;
}
num2 = GCD;

Since remainder is 0, this won't get executed and num2 is set to GCD which you haven't defined, so it will be 0. You see your problem?

firstPerson
Senior Poster
3,923 posts since Dec 2008
Reputation Points: 841
Solved Threads: 608
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: