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.