14个数,求其中几个数之和为一定数的方法。
已知:57.311,57.224,57.131,57.087,56.608,56.081,51.919,50.111,41.059,35.611,16.132,12.524,3.599,1.776.求任几个数之和为279.448.
// 输出为:57311 57131 56081 41059 35611 16132 12524 3599 #include <stdio.h> int main() { const unsigned a[14] = { 57311,57224,57131,57087,56608,56081,51919,50111,41059,35611,16132,12524,3599,1776 }; const unsigned b = 279448; size_t c[14] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }; for( ; ; ) { unsigned sum = 0; for( size_t i=0; i!=14 && c[i]<14; ++i ) sum += a[c[i]]; if( sum == b ) { for( size_t i=0; i!=14 && c[i]<14; ++i ) printf( " %u", a[c[i]] ); printf( "\n" ); } size_t idx; for( idx=14; idx!=0 && c[idx-1]>13; --idx ); if( idx == 0 ) break; ++c[--idx]; for( size_t i=idx+1; i!=14; ++i ) c[i] = c[idx] + (i-idx); } return 0; }
#include <stdio.h> int main() { const unsigned a[14] = { 57311,57224,57131,57087,56608,56081,51919,50111,41059,35611,16132,12524,3599,1776 }; const unsigned b = 279448; for( unsigned mask=1; mask!=1u<<14; ++mask ) { unsigned sum = 0; for( size_t i=0; i!=14; ++i ) if( mask & (1u<<i) ) sum += a[i]; if( sum == b ) { for( size_t i=0; i!=14; ++i ) if( mask & (1u<<i) ) printf( " %u.%03u", a[i]/1000, a[i]%1000 ); printf( "\n" ); } } return 0; }输出