GCD AND LCM - this program is showing wrong answer

GCD AND LCM - this program is showing wrong answer

#include <stdio.h>
int gcd(int a,int b);
int main()
{
    int t,a,b,hcf,lcm;
    scanf("%d\n",&t);
    while(t--)
    {
        scanf("%d %d",&a,&b);
        hcf = gcd(a,b);
        lcm = (a*b)/hcf;
        printf("%d %d\n",hcf,lcm);
    }
    return 0;
}
int gcd(int a,int b)
{
    int dividend = a>= b ? a:b;
    int divisor = a<= b ? a : b;
    while(divisor!=0){
        int remainder = dividend%divisor;
        dividend = divisor;
        divisor = remainder;
    }
    return dividend;
}

Make sure you are giving input in required format. Meaning, if it asked for LCM first and then HCF, then print in required order.

Also, make sure you dont suffer overflow. If numbers are between [1,10^9] , i recommend using long long int in c++, as LCM can cross the limit/data range of int causing overflow and WA.

Without the link to Q, i can only help this much. Please provide link to Q.

1 Like

i think instead of int u have to take long type

import java.io.*;
public class FLOW016 {
/**
* @param args
* @throws IOException
* @throws NumberFormatException
*/
public static void main(String[] args) throws NumberFormatException,
IOException {
// TODO Auto-generated method stub
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
int t, n, i;
t = Integer.parseInt(reader.readLine());
while (t != 0) {

		String s[] = reader.readLine().split(" ");
		int[] arr = new int[2];
		for (i = 0; i < 2; i++) {
			arr[i] = Integer.parseInt(s[i]);
		}
		int small,gcd=1;
		if(arr[0]>arr[1]){
			small=arr[1];
		}else{
			small=arr[0];
		}
		for (int k =1 ; k <=small; k++) {
			if (arr[0]%k==0 && arr[1]%k==0){
				gcd=k;					
			}
			
		}
		int lcm=(arr[0]*arr[1])/gcd;
		
		System.out.println(gcd +" "+lcm);
		t--;
	}
}

}

//