C++中查詢數字是否恰好有四個不同因子的查詢


在這個問題中,我們得到了Q個查詢,每個查詢都有一個數字N。我們的任務是建立一個程式來解決這些查詢,以判斷C++中一個數字是否恰好有四個不同的因子。

問題描述

為了解決每個查詢,我們需要找到數字N是否恰好有四個不同的因子。如果有,則列印YES,否則列印NO。

讓我們舉個例子來理解這個問題:

輸入:Q = 3, 4, 6, 15

輸出:NO YES YES

解釋

對於查詢1:4的因子是1, 2, 4

對於查詢2:6的因子是1, 2, 3, 6

對於查詢3:15的因子是1, 3, 5, 15

解決方案

一個簡單的解決方案是找到該數字的所有因子。這是透過查詢從1到√N的所有數字,並將計數器增加2來完成的。然後檢查計數器是否等於4,並根據其相等性列印YES或NO。

示例

線上演示

#include <iostream>
#include <math.h>
using namespace std;
   int solveQuery(int N){
   int factors = 0;
   for(int i = 1; i < sqrt(N); i++){
      if(N % i == 0){
         factors += 2;
      }
   }
   if(factors == 4){
      return 1;
   }
   return 0;
}
int main() {
   int Q = 3;
   int query[3] = {4, 6, 15};
   for(int i = 0; i < Q; i++){
      if(solveQuery(query[i]))
         cout<<"The number "<<query[i]<<" has exactly four distinct factors\n";
      else
         cout<<"The number "<<query[i]<<" does not have exactly four
      distinct factors\n";
   }
}

輸出

The number 4 does not have exactly four distinct factors
The number 6 has exactly four distinct factors
The number 15 has exactly four distinct factors

一種有效的方法是使用數論中關於四個因子數的概念。因此,如果一個數字有四個因子,則:

  • 如果該數字是素數的立方。那麼它將有四個不同的因子。例如,如果N = (p^3),則因子將是1, p, (p^2), N。

  • 如果該數字是兩個不同素數的乘積。那麼它也將有四個不同的因子。例如,如果N = p1*p2,則因子將是1, p1, p2, N。

示例

線上演示

#include <bits/stdc++.h>
using namespace std;
int N = 1000;
   bool hasFourFactors[1000];
   void fourDistinctFactors() {
      bool primeNo[N + 1];
      memset(primeNo, true, sizeof(primeNo));
      for (int i = 2; i <= sqrt(N); i++) {
         if (primeNo[i] == true) {
            for (int j = i * 2; j <= N; j += i)
               primeNo[j] = false;
         }
      }
      vector<int> primes;
      for (int i = 2; i <= N; i++)
         if (primeNo[i])
            primes.push_back(i);
            memset(hasFourFactors, false, sizeof(hasFourFactors));
   for (int i = 0; i < primes.size(); ++i) {
      int p1 = primes[i];
      if (1 *(pow(p1, 3)) <= N)
         hasFourFactors[p1*p1*p1] = true;
      for (int j = i + 1; j < primes.size(); ++j) {
         int p2 = primes[j];
         if (1 * p1*p2 > N)
            break;
         hasFourFactors[p1*p2] = true;
      }
   }
}
int main() {
   int Q = 3;
   int query[] = {3, 6, 15};
   fourDistinctFactors();
   for(int i = 0; i < Q; i++){
      if(hasFourFactors[query[i]])
         cout<<"The number "<<query[i]<<" has exactly four distinct
         factors\n";
      else
         cout<<"The number "<<query[i]<<" does not have exactly four distinct factors\n";
   }
   return 0;
}

輸出

The number 3 does not have exactly four distinct factors
The number 6 has exactly four distinct factors
The number 15 has exactly four distinct factors

更新於:2020年10月9日

322 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.