Factorization Prime Factor Algorithm

Source: Internet
Author: User

 

# Include <stdio. h> <br/> # include <math. h> <br/> int main () <br/>{< br/> int n, I; <br/> while (scanf ("% d", & n) & n) <br/>{< br/> for (I = 2; I <= sqrt (n); I ++) <br/> if (n % I = 0 & (n/= I) <br/> printf ("% d", I --); <br/> printf ("% d/n", n); <br/>}< br/> return 0; <br/>}< br/>

 

 

Someone asked me how the program works.

 

Decompose n into prime factors

 

General method: Each I from 2 to sqrt (n) is divided by n. If I can be divisible, it is determined whether I is a prime number, if yes, I is a qualitative factor of n, and then n = n/I, And then I is returned to 2, and then the quality factor of n is searched.

 

My optimization: the general idea remains unchanged and some pruning is performed. First, I try to divide each I from 2 to sqrt (n) by n. If I can divide n, so we don't need to judge I, I must be the quality factor of n, and n = n/I, because n may have multiple identical quality factors. To avoid omission, we only need to set I --, when the next loop is skipped, It is offset by I ++. The value of I remains unchanged because it ranges from 2 ~ Each number of I has already determined whether it can divide n. Therefore, it is not necessary to roll back I to 2. The value of I remains unchanged when I jumps to the next loop, in the end, n will be converted into a prime number, which is also a prime factor. Therefore, writing a program is the code at the beginning. As for efficiency, I think it is still relatively high ..

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.