序列求和
题:输入两个正整数a的n,求a+aa+aaa+...+a(n个a)之和。例如输入2和3 ,输出2+22+222.(请大神指教,多谢)
/* 分析过程,以2/7为例: 2 22 222 2222 22222 222222 2222222 value7 = 2469134 n = 7 2 22 222 2222 22222 222222 value6 = 246912 n = 6 2 22 222 2222 22222 value5 = 24690 n = 5 2 22 222 2222 value4 = 2468 n = 4 2 22 222 value3 = 246 n = 3 2 22 value2 = 24 n = 2 2 value1 = 2 n = 1 通过结果集可总结出规律如下 n = 1时,结果 value1 = a = 2; n = 2时,结果 value2 = 24 也就是 value1 * 10 + n * 2; n = 3时,结果 value3 = 246 也就是 value2 * 10 + n * 2; 得出算法为: int num =0; for(int i=1; i<=n; i++) { num = num * 10 + i * a; } */ //实现: #include <iostream> using namespace std; int main() { long long a, n; cin >> a >> n; long long num = 0; for (int i = 1; i <= n; i++) { num = num * 10 + i * a; } cout << "result:" << num << endl; system("pause"); return 0; }
[此贴子已经被作者于2018-10-27 22:49编辑过]
#include <iostream> #include <string> using namespace std; int main() { while (true) { string a, str; int n, value = 0; cin >> a >> n; for (int i = 0; i < n; i++) { str += a; value += atoi(str.c_str()); } cout << value << endl; } system("pause"); return 0; }
#include <string> std::string foo( unsigned a, unsigned n ) { if( a==0 || n==0 ) return "0"; // 当 a==9 且 n>1 时,结果是 n+1 位;其它情况结果都是 n 位 unsigned m = n + (a==9 && n>1); std::string result( m, '0' ); for( unsigned carry=0; m--; --n) { carry += n*a; result[m] = carry%10 + '0'; carry /= 10; } return result; } #include <iostream> using namespace std; int main( void ) { unsigned a, n; cin >> a >> n; cout << foo(a,n) << endl; }