Blue Bridge Cup - Lucky Number (Simulation)

The main idea of ​​the title: According to the conditions of the lucky number, the multiples of the lucky number are continuously deleted, and the lucky number is left. What is required is the number of lucky numbers in a certain interval.

Question analysis: This question directly simulates the steps of deletion, you can get an array of lucky numbers, and then find the number of lucky numbers in a given interval in the array.

Code explanation: First remove the multiples of 2 from the array, then there are only 1, 3, 5, 7, 9, 11, 13 left in the num array...

Then I take the second number in the array, which is 3, and delete all the numbers whose positions are multiples of 3, that is, keep the numbers that are not multiples of 3.

After such a loop, the num array becomes 1, 3, 7, 9, 13...

Then take the third number 7 in the array, so k in the code increments by 1 after each loop, indicating that this time the next lucky number is a multiple.

Finally, take out the number of lucky numbers in the given interval.

Code display:

#include <iostream>
#include <string.h>
using namespace std;

int main(){
    int m,n;
    cin>>m>>n;
    int num[n];
    memset(num,0,sizeof(num));
    for(int i=1;i<n;i++)
        num[i] = i*2-1; //First remove the multiple of 2
    int temp = 0;
    int k=2;
    int j = 1;
    do{
        temp = num[k++]; //Get the current lucky number, then the multiple of the lucky number will be deleted
        for(int i=1;i<n;i++){
            if(i%temp!=0)
                num[j++] = num[i]; //Keep the lucky number in the current array
        }
        j = 1;
    }while(temp<n);
    int count = 0;
    for(int i=1;i<n;i++){
        if(num[i]>=n)
            break;
        if(num[i]>m)
            count++;
    }
    cout<<count<<endl;
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326014633&siteId=291194637