簡體   English   中英

如何使用給定數量的除數 output 所有數字? (C++)

[英]How do I output all numbers with a given amount of divisors? (C++)

我需要輸入 2 個整數,n 和 k,n 是范圍,k 是這些數字的除數數量,並且只顯示具有 k 個除數的數字。

#include <iostream>

using namespace std;

int main()
{
    int n, k,cnt=0;
    cin>>n;
    cin>>k;
    for(int i=1; i<=n; i++)
    {
        if(n%i==0)
        {
                cnt++;
        }
        if(k==cnt)
            cout<<i<<" ";
    }

return 0;
}
#include <bits/stdc++.h>
using namespace std;

int main(){
    int n, k;
    cin>>n>>k;
    for(int i = 1; i <= n; i++){
        int num_divisors_i = 0; 
        for (int j = 1, len = sqrt(i); j <= len; j++) { 
            if (i % j == 0) { 
                if (i / j == j) {
                    num_divisors_i++;  
                }  
                else {
                    num_divisors_i = num_divisors_i + 2; 
                }
            } 
        } 
        if(num_divisors_i == k) cout<<i<<" has "<<k<<" divisors"<<endl;
    } 
}

這是我的解決方案:

#include<iostream>

int main(int argc, char* argv[]) {

    int n = 0, k = 0;

    std::cout << "Enter the range: ";
    std::cin >> n; if (!std::cin) throw std::runtime_error("range read failed");
    std::cout << std::endl << "Enter the number divisors: ";
    std::cin >> k; if (!std::cin) throw std::runtime_error("number of divisors read failed");
    std::cout << "numbers with " << k << " divisor:: ";
    for (int i = 1; i != n+1/*if k is inclusive else n*/; ++i) {
        int cnt = 0;
        for (int j = 1; j != i+1; ++j) {
            if (i % j == 0)
                cnt += 1;
        }
        if(cnt == k)
            std::cout << i << ' ';
    }


    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM