【发布时间】:2014-05-02 07:04:55
【问题描述】:
我需要找出用户输入的数字的质因数
例子:
输入一个数字: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++还是个初学者
【问题讨论】:
-
您正在使用一个函数。你认为
main()是什么? -
@wallyk:或者更有趣的是
ceil和sqrt。
标签: c++ primes prime-factoring