簡體   English   中英

在沒有函數的情況下找到給定數量c ++的素因

[英]finding prime factors of a given number c++ without functions

我需要找到用戶輸入的數字的主要因素

例:

輸入數字:1430。1430的素數是2,5,11,13

我寧願不使用函數,因為我還沒有介紹它

這是我的代碼

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std ;

int main () 
{
    int count, i , i2 ;
    int userInput, prime ;
    bool flag = false ;

    cout << "Enterr: " ;
    cin >> userInput ;
    cout << "The prime factors are: " ;
    for (i = 2; i < userInput ; i++)
    {
        if (userInput % i == 0) // this for loop is to check is the counter (i) is a multiple of userInput
        {   
            prime = i;
            // the next for loop is to check is the multiple is a prime number
            for( i2 = 2; i2< ceil(sqrt(prime))  ; i2++)
            {
                if (prime % i2 == 0)
                    flag = true ;
            }
        }
        if (flag == false ) 
            cout << i << ", "  ;
        flag = false ;
    }

    cout<< endl ;

    return 0 ;
}

我的輸出完全忽略第二個循環,只輸出所有小於userInput整數

我能夠創建一段代碼來檢查數字是否為素數:

#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std ;

int main () 
{
    int userInput, prime ;
    int i ;
    bool flag = false ;

    cin >> userInput ;

    for( i = 2; i < static_cast<int>(sqrt(userInput) + 1) ; i++)
    {
        if (userInput % i == 0)
            flag = true;        
    }

    if (flag == false ) 
        cout << "Number is a prime" << endl ;
    else
        cout << "Number is not a prime " << endl ;

    return 0 ; 
}

對不起,如果有任何錯誤。 我仍然是C++的初學者

您快到了-您只需要移動此方塊

  if (flag == false )
          cout << i << ", "  ;
      flag = false ;

進入你的

if (userInput % i == 0)

塊(您只想打印輸入數字的因數),一切都很好。

如果按查找順序將除數除以數字,則無需測試查找的偶數的素數,同時按升序枚舉候選數:

    for (i = 2; i <= userInput/i;  )
    {
        if (userInput % i == 0) 
        { 
            cout << i << ", ";   // i is a prime factor of the original
            userInput /= i;      //   number in userInput
        }
        else
            ++i;
    }
    if (userInput > 1)
    {
        cout << userInput;       // the biggest prime factor of the original
    }                            //   input number 

這樣找到的輸入數字的素數也按升序打印。

您是否嘗試調試(甚至在精神上)程序中發生了什么? 我對此表示懷疑,否則您會注意到以下情況:

if (userInput % i == 0)

對於所有除數都將為假。 這意味着您將直接去檢查

if (flag == false ) 

這是正確的,因為您沒有將標志更改為true,因此錯誤地將數字作為主要因素。

您還應該考慮一些特殊情況。 例如,素數的素數因子僅僅是素數本身(您永遠無法輸出素數( i < userInput;

關於無功能限制:您無法避免使用功能,否則您的代碼將無法執行任何操作。 但是,您可以避免看起來像函數調用的事情(看起來像name() )。

要消除sqrtceil ,應將條件重新設置為i2 * i2 <= prime

暫無
暫無

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

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