Print the highest prime factor of a composite number in C

I solved a riddle where im was required to find the largest Prime Factor of the compound number entered by the user. I thought and tried something, but he fails to discover the biggest simple factor among the factors of the composite number.

I am adding my code below, I would appreciate if anyone could help me here to discover the biggest prime no. among 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);
}
+1
source share
6 answers

, c, .

, F ( 2), C/F . C/F C.

: , . , , , i , . , - :

is_prime = true;

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

if (is_prime)
    largest_prime = x;

, , x, 2. x. sqrt() <math.h> , , .

+3

b = i, , i. b = i, , i.

( "", " 2 sqrt(i)", )

+1

, 2 sqrt (N). , . , .

, . .

+1

, , - , , 52, . , , , , , .

#include<stdio.h>

void main () {int i, j, b = 2, c; printf ("\ nEnter a compound number:"); scanf ("% d", & c); printf ("Factors:");

for(i=1; i<=c/2; i++)
{
    if(c%i==0)
    {
        printf("%d ", i);
        for(j=1; j<=i; j++) //since a numbr cand be divisible by a number greated than its half
        {               if(i%j > 0)
                b = i; //b stores the largest prime factor
            if(b%3==0)
                b = 3;
                else if(b%2==0)
                b=2;
              else if(b%5==0)
                b=5;
                }
    }
}


printf("%d\nLargest prime factor: %d\n", c, b);

}

0
source

In Python, something like this will do:

import math
import itertools

# largest prime factor of a composite number
def primality(num):
    for i in range(2,int(math.sqrt(num))+1):
        if num%i ==0:
             return 0
    return 1

if __name__ == '__main__':
    number = 600851475143
    for i in itertools.count(2,1):
            if number%i == 0:
                if number%10 in [7,9,1,3] and primality(number/i):
                    print number/i
                    break

What I did to test for primitiveness is a neat square root method.

0
source

Source: https://habr.com/ru/post/1759391/


All Articles