给我们一个大小为N的数组。该数组最初的全为0。任务是计算编号。N个移动后数组中1的个数。每第N次移动都有一个关联规则。规则是-
第一次移动-在位置1、2、3、4…………..处更改元素。
第二次移动-在位置2、4、6、8…………..处更改元素。
第三步-在位置3、6、9、12…………..处更改元素。
计算最后一个数组中的1。
让我们通过示例来理解。
输入值
Arr[]={ 0,0,0,0 } N=4输出结果
Number of 1s in the array after N moves − 2
说明-后续移动后的数组-
Move 1: { 1,1,1,1 }
Move 2: { 1,0,1,0 }
Move 3: { 1,0,0,3 }
Move 4: { 1,0,0,1 }
Number of ones in the final array is 2.输入值
Arr[]={ 0,0,0,0,0,0} N=6输出结果
Number of 1s in the array after N moves − 2
说明-后续移动后的数组-
Move 1: { 1,1,1,1,1,1,1 }
Move 2: { 1,0,1,0,1,0,1 }
Move 3: { 1,0,0,1,0,0,1 }
Move 4: { 1,0,0,0,1,0,0 }
Move 5: { 1,0,0,0,0,1,0 }
Move 4: { 1,0,0,0,0,0,1 }
Number of ones in the final array is 2.我们采用一个以0和整数N初始化的整数数组Arr []。
函数Onecount将Arr []的大小作为N输入,并返回no。N移动后,最终数组中的第一个。
for循环从1开始直到数组结尾。
每个i代表第i个动作。
嵌套的for循环从第0个索引开始到数组末尾。
对于第ith次移动,如果索引j为i的倍数(j%i == 0),则在该位置将0替换为1。
每个i都将继续此过程,直到数组结束。
注-索引从i = 1,j = 1开始,但数组索引从0到N-1。因此,每次都会对arr [j1]进行转换。
最后再次遍历整个数组并计数。1的个数并存储在计数中。
返回计数为所需结果。
#include <stdio.h>
int Onecount(int arr[], int N){
   for (int i = 1; i <= N; i++) {
      for (int j = i; j <= N; j++) {
         // If j is divisible by i
         if (j % i == 0) {
            if (arr[j - 1] == 0)
               arr[j - 1] = 1; // Convert 0 to 1
            else
               arr[j - 1] = 0; // Convert 1 to 0
         }
      }
   }
   int count = 0;
   for (int i = 0; i < N; i++)
      if (arr[i] == 1)
         count++; // count number of 1's
   return count;
}
int main(){
   int size = 6;
   int Arr[6] = { 0 };
   printf("Number of 1s in the array after N moves: %d", Onecount(Arr, size));
return 0;
}输出结果
如果我们运行上面的代码,它将生成以下输出-
Number of 1s in the array after N moves: 2