1. 程式人生 > >程式設計與演算法 第六週測驗

程式設計與演算法 第六週測驗

1:Pell數列

#include <iostream>
using namespace std;
int main()
{
  int n;
  long k;
  long long P[1000000+1]={0};
  P[1]=1;
  P[2]=2;
  for (long i=3;i<=1000000; i++)
    P[i] = (2 * P[i-1] + P[i-2])%32767;
  cin >> n;
  while (n--)
  {
    cin >> k;
    cout << P[k] << endl;
  }
  return
0; }

2:求最大公約數問題

#include <iostream>
using namespace std;
long long gy(long long a, long long b)
{
  if (a%b==0)
    return b;
  return gy(b, a%b);
}
int main()
{
  long long a,b;
  cin >> a >> b;
  cout << gy(a, b) << endl;
  return 0;
}

3:程式設計填空:第i位替換

#include <iostream>
using namespace std; int bitManipulation1(int n, int m, int i) { // 在此處補充你的程式碼 return (((m>>i)&1) == 0) ? (n & (~(1<<i))) : (n | (1<<i)); } int main() { int n, m, i, t; cin >> t; while (t--) { cin >> n >> m >> i; cout << bitManipulation1(n, m, i) << endl; } return
0; }

4:程式設計填空:第i位取反

#include <iostream>
using namespace std;

int bitManipulation2(int n, int i) {
// 在此處補充你的程式碼
  return (((n>>i)&1)==0) ? (n | 1<<i) : (n & (~(1<<i)));
}

int main() {
    int t, n, i;
    cin >> t;
    while (t--) {
        cin >> n >> i;
        cout << bitManipulation2(n, i) << endl;
    }
    return 0;
}

5:程式設計填空:左邊i位取反

#include <iostream>
#include <bitset>
using namespace std;

int bitManipulation3(int n, int i) {
// 在此處補充你的程式碼
  cout << bitset<sizeof(int)*8>(n) << endl;
  cout << bitset<sizeof(int)*8>((unsigned int)n>>(sizeof(n)*8-i)) << endl;
  cout << bitset<sizeof(int)*8>(~(n>>(sizeof(n)*8-i))) << endl;
  cout << bitset<sizeof(int)*8>((~(n>>(sizeof(n)*8-i)))<<(sizeof(n)*8-i)) << endl;
  cout << endl;
  unsigned long m = (unsigned int)n;
  int o = (int)(((m<<i)&(0x0ffffffff))>>i);
  cout << n << " " << i << " " << m << endl;
  cout << bitset<sizeof(int)*8>(n<<i) << endl;
  cout << bitset<sizeof(int)*8>(m<<i) << endl;
  cout << bitset<sizeof(int)*8>(o) << endl;
  cout << bitset<sizeof(int)*8>( ((~(n>>(sizeof(n)*8-i)))<<(sizeof(n)*8-i)) + (int)((((unsigned long)n<<i)&(0x0ffffffff))>>i) )<< endl;
  return ((~(n>>(sizeof(n)*8-i)))<<(sizeof(n)*8-i)) + (int)((((unsigned long)n<<i)&(0x0ffffffff))>>i);
}

int main() {
    int t, n, i;
    cin >> t;
    while (t--) {
        cin >> n >> i;
        cout << bitManipulation3(n, i) << endl;
    }
    return 0;
}

6:程式設計填空:計算整數k

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
    unsigned int t, n, i, j, m, mi, mj;
    cin >> t;
    while (t--) {
        cin >> n >> i >> j;
        mi = (n>>i)&1;
        mj = (((n>>j)&1)==0)?1:0;
        m = (mi<<i) + (mj<<j);
        for (unsigned int k=i+1; k<j; k++)
          m += 1<<k;
        cout << setbase(16) << m << endl;
    }
    return 0;
}

-eof-