Poj1775-sum of factorials

Source: Internet
Author: User

Question: give an n and ask if N can be composed of some factorial and if yes can be output, otherwise no can be output.

-1 indicates the end
Solution: Because n does not exceed 1,000,000, let's calculate 9 when n = 9! = 362880, that is, 10! Yes

It is greater than 1000000, so the maximum factorial is 9 !, Therefore, we will create a table using the factorial from 1 to 9, and then use a backpack or a profiteering search.

Can easily solve this problem.

# Include <iostream> using namespace STD; # define maxf 10 // The maximum value is 10 class CFAC {public: CFAC (int n); CFAC ();~ CFAC (); void setans (int n); int run (INT cur, int sum); Private: int m_nans; int m_nfacarr [maxf] ;}; CFAC: CFAC () {m_nfacarr [0] = 1; // special, 0! = 1for (INT I = 1; I <maxf; I ++) {// calculate the factorial m_nfacarr [I] = m_nfacarr [I-1] * I;} CFAC: CFAC (INT N) {CFAC (); m_nans = N;} void CFAC: setans (int n) {m_nans = N;} int CFAC: Run (INT cur, int sum) {// If (sum = m_nans) return 1; if (cur> = maxf) return 0; If (sum> m_nans) return 0; if (run (cur + 1, sum + m_nfacarr [cur]) return 1; return run (cur + 1, sum);} CFAC ::~ CFAC () {} int main () {int N; cfac fac; while (CIN> N) {If (n <0) break; If (n = 0) {cout <"no" <Endl; continue;} FAC. setans (n); If (FAC. run () {cout <"yes" <Endl ;}else {cout <"no" <Endl ;}} return 0 ;}

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.