[英]given prime factorization of a number iterate through all factors in c++ without recursion
[英]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()
)。
要消除sqrt
和ceil
,应将条件重新设置为i2 * i2 <= prime
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.