Classical algorithm detailed (12) Decomposition factorization

Source: Internet
Author: User

Title: It is well known that any composite (which is more than 1 and itself) can be written in several prime-number multiplication forms, which are called the composite's mass factor. For example, 24=2x2x2x3. The form of multiplying a composite into several prime numbers is called decomposition factorization. For a prime number, his qualitative factor can be defined as itself. Write a program to implement the decomposition factorization.

C + + implementation

1#include <iostream>2 3 using namespacestd;4 5 intIsPrime (intN) {6      for(inti =2; I < n; i++) {7         if(n%i = =0)8             return 0;9     }Ten     return 1; One } A  - intGetprimefactor (intN) {//you can return no value, where 1 indicates an error, and return 1 indicates normal.  -     if(N <2) the         return-1; -     if(IsPrime (n)) { -cout << N <<"\ t"; -         return 1; +     } -     Else { +          for(inti =2; I < n; i++) { A             if(n%i = =0) { atcout << i <<"\ t"; -Getprimefactor (N/i); -                  Break; -             } -         } -     } in     return 1; - } to  + intMainintargcChar*argv[]) { -     intA; theCIN >>A; * Getprimefactor (a); $ GetChar ();Panax Notoginseng GetChar (); -     return 0; the}

Idea: First write a function to determine whether a number is a prime, followed by a recursive method, a number divided by its minimum quality factor after the value is a quality factor decomposition of the value, the problem is the same size reduction, so is a recursive problem, the termination condition is that the number is a prime. It can be printed when it is a prime number or when a minimum quality factor is found.

Classical algorithm detailed (12) Decomposition factorization

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.