C++中计算范围内质因数只有2和3的数字


我们给出两个数字START和END来定义一个数字范围。目标是找到在这个范围[START,END]内,其质因数只有2和3的数字。

我们将遍历从START到END的数字,并对每个数字检查其是否仅能被2和3整除。如果可以整除,则将其除以2或3并减少其值。如果不能,则中断循环。最终,如果数字被减小到1,则它只有2和3作为其质因数。

让我们用例子来理解。

输入 

START=20 END=25

输出 

Numbers with only 2 and 3 as prime factors: 1

说明 

Prime factors of each number:
20 = 2*2*5
21 = 3*7
22 = 2*11
23 = 1*23
24 = 2*2*2*3
25 = 5*5
Only 24 has 2 and 3 as prime factors.

输入 

START=1000 END=1500

输出 

Numbers with only 2 and 3 as prime factors: 4

说明 

1024 1152 1296 1458 are the numbers with only 2 and 3 as prime factors

下面程序中使用的算法如下:

  • 我们将整数START和END作为范围变量。

  • 函数twothreeFactors(int start, int end)接受范围变量并返回质因数只有2和3的数字个数。

  • 将初始变量count设置为0,用于统计此类数字。

  • 使用for循环遍历数字范围。i=start到i=end

  • 现在,对于每个数字num=i,使用while循环检查是否num%2==0,如果成立则除以2。

  • 如果num%3==0,则除以3。如果都不能整除,则中断while循环。

  • 如果while循环结束后num为1,则增加count的值。

  • 所有循环结束后,count将包含质因数只有2和3的数字总数。

  • 返回count作为结果。

示例

 在线演示

#include <bits/stdc++.h>
using namespace std;
int twothreeFactors(int start, int end){
   // Start with 2 so that 1 doesn't get counted
   if (start == 1)
      { start++; }
   int count = 0;
   for (int i = start; i <= end; i++) {
      int num = i;
      while(num>1){
         // if divisible by 2, divide it by 2
         if(num % 2 == 0)
            { num /= 2; }
         // if divisible by 3, divide it by 3
         else if (num % 3 == 0)
            { num /= 3; }
         else //if divisible by neither 2 nor 3 break
            { break; }
      }
      // means only 2 and 3 are factors of num
      if (num == 1)
         { count++; }
   }
   return count;
}
int main(){
   int START = 10, END = 20;
   cout <<"Numbers with only 2 and 3 as prime factors:"<< twothreeFactors(START,END);
   return 0;
}

输出

如果运行以上代码,它将生成以下输出:

Numbers with only 2 and 3 as prime factors:3

更新于:2020年10月31日

670 次浏览

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.