本文介绍了打印在C复合数量最大素因子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我解决一个难题,在需要IM找到用户输入一个合数中最大的主要因素。
我想到的东西,都尝试过了,但它不管理,以检测最大素因子之间的合数的因素。

我在我追加下面code,我会很感激,如果有人可以帮助我在这里得到检测最大素无。其中包括的因素并打印。

  //接受来自用户的合数,并打印其最大的主要因素。#包括LT&;&stdio.h中GT;
无效的主要()
{
    INT I,J,B = 2,C;
    的printf(\\ n输入一个合数:);
    scanf函数(%D,和C);
    的printf(因素:);    对于(i = 1; I< = C / 2;我++)
    {
        如果(C%我== 0)
        {
            的printf(%D,我);
            为(J = 2; J&下; = I / 2; J ++)//由于numbr CAND是由greated比其半数整除
            {如果(I%J&0)
                    B =;
                否则,如果(我== 3)
                    B = 3;
            }
        }
    }
    的printf(%d个\\ nLargest素因子数:%d \\ n,C,B);
}


解决方案

关键是要找到在最小因子F(2起),其中C / F是一个素数。然后,C / F将是C的最大的主要因素。

编辑:看起来你也想列出所有的因素。问题是,在你的内部循环,对于基本测试,您设置的最大素数 I 对于整除与任何数字。换句话说,尝试这样的事情:

  is_prime = TRUE;为(J = 2; J&下; = X / 2; J ++){
    如果(我引用%j == 0)
        is_prime = FALSE;
}如果(is_prime)
    largest_prime = X;

请注意,你可以真正停止越早大于x除以2。你可以在x的平方根停止。但是,的sqrt()函数<文件math.h> 是有点乱,以你的情况与工作因为它与浮点数,不是整数。

I was solving a puzzle, where im required to find the largest Prime Factor of a composite number entered by the user.I thought of something and have tried it out, but it doesn't manage to detect the largest prime factor amongst the factors of the composite number.

I'm appending my code below, I'd be grateful if anyone could help me out here to get to detect the largest prime no. amongst the factors and print it.

// Accept a composite number from user and print its largest prime factor.

#include<stdio.h>
void main()
{
    int i,j,b=2,c;
    printf("\nEnter a composite number: ");
    scanf("%d", &c);
    printf("Factors: ");

    for(i=1; i<=c/2; i++)
    {
        if(c%i==0)
        {
            printf("%d ", i);
            for(j=2; j<=i/2; j++) //since a numbr cand be divisible by a number greated than its half
            {               if(i%j > 0) 
                    b = i;
                else if(i==3)
                    b = 3;
            }
        }
    }
    printf("%d\nLargest prime factor: %d\n", c, b);
}
解决方案

The trick is to find the smallest factor F (starting from 2) where C / F is prime. Then, C / F will be the largest prime factor of C.

Edit: It looks like you also want to list all the factors. The problem is, in your inner loop that tests for primality, you set the largest prime to i for numbers that are divisible with anything. In other words, try something like this:

is_prime = true;

for (j = 2; j <= x / 2; j++) {
    if (i % j == 0)
        is_prime = false;
}

if (is_prime)
    largest_prime = x;

Note that you could actually stop sooner than x divided by 2. You could stop at the square root of x. However, the sqrt() function in <math.h> is a bit messy to work with in your case because it works with floating point numbers, not integers.

这篇关于打印在C复合数量最大素因子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 13:40