简体   繁体   English

找出n个数字的公因子数(不包括“ 1”作为公因子)

[英]Find the number of common factors for n numbers excluding “1” as common factor

Here is my code that i have written in gcc. 这是我用gcc编写的代码。 Don't know if my logic is incorrect or i'm making some other mistake.The output is coming as 0 every time. 不知道我的逻辑是不正确还是我在犯其他错误。每次输出都为0。

int main()
{
int n,a[20],count=0;
cin>>n;

for(int i=0;i<n;i++)
{
    cin>>a[i];
}

for(int k=0;k<n;k++)
{
    int c=0;
    for(int j=2;j<n;j++)
    {
        if(a[k]%j==0)
        {
            c++;
        }
        else
        {
            continue;
        }
    }
    if(c==n)
    {
      count++;
    }
}
cout<<count;
}

Your approach isn't correct from what I gather. 根据我的收集,您的方法是不正确的。 You should take every number from 2 to max(a) [1] and check if it is a factor/divisor of every number in a . 你应该采取一切数量从2max(a) [1],并检查它是否在每一个数字的因子/除数a If it is, you can increment count . 如果是,则可以增加count


[1] or even better max(sqrt(a[i]) for a[i] in a) in pseudo-code-ish syntax. 在伪代码形式语法中,[1]甚至max(sqrt(a[i]) for a[i] in a)甚至更好。

You got the loops in the wrong order. 您以错误的顺序获得了循环。 You are checking if there are n dividers of any of the numbers. 您正在检查是否有任何数字的n分频器。

Try swapping the loops. 尝试交换循环。 Then the count will be of the number of numbers that divide the input. 然后,该计数将是将输入相除的数字的数量。

You also have the wrong upper bound. 您的上限也有误。 You need the highest possible divider. 您需要最高的分频器。

int max_divider = 2;
for (i = 0; i < n; i++) {
    if (a[i] > max_divider) 
    {
        // Naive approach
        max_divider = a[i];
    }
}
// For each number 2..max_divider
for(int j=2;j <= max_divider;j++)
{
    int c=0;
    for(int k=0;k<n;k++)
    {
        if(a[k]%j==0)
        {
            c++;
        }
        else
        {
            continue;
        }
    }
    if(c==n)
    {
      count++;
    }
}

Replace this loop 替换此循环

for(int j=2; j<n; j++)

with

for(int j=2; (j < a[k]); j++)

Note that you can get rid of else part, it is having no effect. 请注意,您可以摆脱else部分,它没有任何作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM