HCF of negative numbers

Mission Coding

When I input two negative numbers in my program that finds the LCM and HCF of a number, the HCF returns 0. It works fine for positive numbers. Here is the code for HCF module. What can I do to fix it?

static int hcf(int x, int y){
    int hcf = 0;
    for (int i = x; i>=1; i--){
        if (y%i==0 && x%i==0){
            hcf = i;
            break;
        }
    }
    return hcf;
}
Luiggi Mendoza

If x is less or equal to 0, i will be initialized with x value and the for loop won't execute anything due to the condition i >= 1, thus the method will return 0.

Probably you should try to initialize i to (int)Math.abs(x).

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

HCF负数

来自分类Dev

PROLOG-number of positive and negative numbers

来自分类Dev

数论-因素,HCF和LCM

来自分类Dev

HCF Python 程序未调试

来自分类Dev

Negative floating point numbers are not sorted correctly using awk or sort

来自分类Dev

查找hcf和lcm的python程序

来自分类Dev

查找HCF的C代码有什么问题?

来自分类Dev

查找HCF的C代码有什么问题?

来自分类Dev

Negative numeric argument in Vim

来自分类Dev

Arduino Arithmetic error negative result

来自分类Dev

Timeval structs: negative delay with libpcap

来自分类Dev

Python Regex Variable Negative Lookbehind

来自分类Dev

create list with negative value permutation

来自分类Dev

Java: Why does "long" number get negative?

来自分类Dev

Why does C support negative array indices?

来自分类Dev

How to Convert a negative milliseconds into correct timeZone in Java

来自分类Dev

Regular Expression Letter followed by numbers or numbers and a letter

来自分类Dev

How to read numbers in text file as numbers in to list?

来自分类Dev

Generating sequence numbers in Java

来自分类Dev

Numbers in kotlin is not serializable

来自分类Dev

Oracle sequence - skipped numbers

来自分类Dev

Angular order by numbers with decimals

来自分类Dev

Increment Numbers in URL?

来自分类Dev

Git in excel or numbers

来自分类Dev

Image in the top div always hide the bottom div with a negative margin

来自分类Dev

check positive or negative without using conditional statements in java

来自分类Dev

change all negative values in a column of a data frame to zero

来自分类Dev

What is the essential difference between the two functions to find the first negative entry?

来自分类Dev

Why Integer.toBinaryString returns 32 bits if the argument is negative?

Related 相关文章

热门标签

归档