A thinking problem && recursive cycle change

 

 

Ideas:

For example, 52

12345--> 12453 begins, this time becomes 1. The remaining 5 4512, now only need to find the corresponding 1234. n-1, k is the number corresponding to the number of the original map. Eg 1 -> 3 1 + 2 mod 5,4 -> 1 is 4 + 2 mod 5.

This creates a recursion.

Such a recursive left to the last number, the result is this number.

This problem is after mod n from 0,

Solution 1: return +1

#include <iostream>

using namespace std;

int A(int n, int k) {

    if ( n == 1){
        return 1;
    }
    else{
        return (A(n-1,k)+k)%n+1;
    }


}

int main()
{
    int n, k;
    while (true)
    {
       cin >> n;
    cin >> k;
    cout << A(n,k);
    }
    
    
    system("pause");
    return 0;
}

 

解决办法2:将所有数-1,最后加一

#include <iostream>

using namespace std;

int A(int n, int k) {

    if ( n == 1){
        return 0;
    }
    else{
        return (A(n-1,k)+k)%n;
    }


}

int main()
{
    int n, k;
    cin >> n;
    cin >> k;
    cout << A(n,k+1) + 1;
    return 0;
}

 

这样栈会溢出(n很大的时候)

改成循环(解法2)

#include <iostream>

using namespace std;

int A(int n, int k) {

   
    int ans=0,s=1;
    while(s<n){
        s++;
        ans=ans+k;
        ans=ans%s;
    }
    return ans;

}

int main()
{
    int n, k;
    cin >> n;
    cin >> k;
    cout << A(n,k+1) + 1;
    system("pause");
    return 0;
}

Guess you like

Origin www.cnblogs.com/lqerio/p/12093801.html