zoukankan      html  css  js  c++  java
  • 机试笔记7--数学问题

    1.同模余定理

    定义

    所谓的同余,顾名思义,就是许多的数被一个数d去除,有相同的余数。d数学上的称谓为模。如a=6,b=1,d=5,则我们说a和b是模d同余的。因为他们都有相同的余数1。

    应用

    (a+b)%c=(a%c+b%c)%c;--1

    (a-b)%c=(a%c-b%c)%c;--2

    (a*b)%c=(a%c*b%c)%c;--3

    例题

    S(n)=n^5  求S(n)除以3的余数

    这里的问题是用long long,n的5次幂会越界,所以可以用上面的公式3来进行运算。

    2.最大公约数

    int gcd(int a,int b)
    {
         if(b==0)
            return a;
         else return gcd(b,a%b);  
    }
    int GDC(int a,int b)
    {
        int temp=a<b?a:b;
        for(;temp>0;temp--){
          if((b%temp==0)&&(a%temp==0)){
            break;
          }
        }
        return temp;
    }

    例题1

    给出n个正整数,任取两个数分别作为分子和分母组成最简真分数,编程求共有几个这样的组合。

    就是求两个数的最大公约数为1的个数

    例题2

    分数化简,同除以两个数的最大公约数就可以了

    3.最小公倍数(LCM)

    LCM(x, y) = x * y / GCD(x, y)

    4.斐波那契数列

    F(n) = F(n-1) + F(n-2)

    5.素数判定

    只需要从2遍历搭配sqrt(n)就行了

    6.全排列

    对字符串进行全排列

    方法1.使用next_permutation(start,end)

    #include<bits/stdc++.h>
    using namespace std;
    int main(){
        char s[100];
        cin>>s;
        int len=strlen(s);
        sort(s,s+len);
        
        do{
            cout<<s<<endl;
        }next_permutation(s,s+len);
            return 0;
    }

    2.递归

    终止条件:if(begin>=end) 输出

    permutation(arr,begin,end)=permutation(arr,begin+1,end)即一个数组的全排列等于它的所有子排列

    #include <bits/stdc++.h>
    using namespace std;
    void swap(int &a,int &b)
    {
       int temp=a;
       a=b;
       b=temp;
    }
    
    void permutation(int a[],int s,int e)
    {
       if(s>=e){
         for(int i=0;i<e;i++){
            cout<<a[i];
         }
         cout <<endl;
       }
       else{
          for(int i=s;i<e;i++){
            swap(a[s],a[i]);
            permutation(a,s+1,e);
            swap(a[s],a[i]);
          }
    
       }
    }
    int main()
    {
      int source[30];
        int i, count;
    
        scanf("%d", &count);
    
        // 初始化数组
        for (i = 0; i < count; i++)
        {
            source[i] = i + 1;
        }
        permutation(source,0,count);
        return 0;
    }
     
  • 相关阅读:
    C. Shaass and Lights 解析(思維、組合)
    D. Binary String To Subsequences(队列)(贪心)
    CodeForces 1384B2. Koa and the Beach (Hard Version)(贪心)
    CodeForces 1384B1. Koa and the Beach (Easy Version)(搜索)
    CodeForces 1384C. String Transformation 1(贪心)(并查集)
    CodeForces 1384A. Common Prefixes
    POJ-2516 Minimum Cost(最小费用最大流)
    POJ3261-Milk Patterns(后缀数组)
    HDU-1300 Pearls(斜率DP)
    HDU-4528 小明系列故事-捉迷藏(BFS)
  • 原文地址:https://www.cnblogs.com/Sunqingyi/p/12638849.html
Copyright © 2011-2022 走看看