时间:2014.05.14
地点:基地
心情:连续好几天没写博客了,这几天一直都练车,晚上回来都还累的,后悔当初过于紧张和追求完美,结果一下子挂了~所幸是这次过了,完美的一百分哇
--------------------------------------------------------------------------------
一、题目
正整数序列Q中的每个元素都至少能被正整数a和b中的一个整除,现给定a和b,需要计算出Q中的前几项,例如,当a=3,b=5,N=6时,序列为3,5,6,9,10,12
(1)、设计一个函数void generate(int a,int b,int N ,int * Q)计算Q的前几项
(2)、设计测试数据来验证函数程序在各种输入下的正确性
--------------------------------------------------------------------------------
二、分析
无非是按顺序求出a和b的倍数,于是可相继在a和b的基础上累加,通过比较大小按顺序追加到数组,并向下一个可能数据滑动,这样的时间复杂度为O(n)
三、源码
#include<iostream>
#include<cassert>
using namespace std;
void Generate(int a, int b, int N, int* Q)
{
//Precondition: Parameter a,b and N are positive integer
//Postcondition: Caculate the front N items which every item%a==0 or item%b==0
// and then added to the array Q
assert((a > 0) && (b > 0) && (N > 0));
int current_a = a, current_b = b;
for (int count = 0; count < N; ++count)
{
if (current_a < current_b)
{
Q[count] = current_a;
current_a += a;
}
else if (current_b < current_a)
{
Q[count] = current_b;
current_b+=b;
}
else
{
Q[count] = current_a;
current_a += a;
current_b += b;
}
}
}
int main()
{
size_t a, b, N;
cout << "Please input a b and N" << endl;
cin >> a >> b >> N;
int* p_arr = new int[N];
Generate(a, b, N, p_arr);
cout << "The result are as fllows: " << endl;
for (size_t i = 0; i < N; ++i)
cout << p_arr[i] << " ";
cout << endl;
delete p_arr;
p_arr = nullptr;
return 0;
}