问题描述
//Determine the prime factors of a number
for(i = 2; i <= num; i++) { //Loop to check the factors.
while(num % i == 0) { //While the input is divisible to "i" which is initially 2.
printf("%d ",i); //Print the factor.
num = num / i; //Divide the num by "i" which is initially 2 to change the value of num.
}
}
我知道这是使用 for 循环查找数的质因数的方法。但我不知道如何将输出整数表示为其质因数的乘积。 例如,输入是:10 || 输出是:2 x 5 = 10。我们如何做到这一点? TIA。
解决方法
你应该:
- 保存原始值。
- 在每个质因数之间打印运算符
x
。 - 在最后打印原始值。
#include <stdio.h>
int main(void) {
int num;
int i;
int start_num;
int is_first = 1;
if(scanf("%d",&num) != 1) return 1;
start_num = num; //Save the original value.
//Determine the prime factors of a number
for(i = 2; i <= num; i++) { //Loop to check the factors.
while(num % i == 0) { //While the input is divisible to "i" which is initially 2.
if(!is_first) printf("x "); //Print the operator before second and later operands.
printf("%d ",i); //Print the factor.
num = num / i; //Divide the num by "i" which is initially 2 to change the value of num.
is_first = 0; //Mark that there is already one or more operand.
}
}
printf("= %d\n",start_num); //Print the original value.
return 0;
}
,
我已经修改了代码,以提供比我之前发布的更健壮一些的东西,同时也稍微提高了效率。我再次假设您希望通过以下范围内的标准输入进行(无符号)32 位输入:SQLQuery sqlQuery = hibernateTemplate.getSession().createSQLQuery(query);
sqlQuery.setParamer(...) // set the parameters you need
List result = sqlQuery.list();
就算法而言,显然搜索因子只需要测试最多 [1,2^32 - 1]
的候选。还有具有多重性的因子,例如,floor(sqrt(num))
。
此外,在分解出 (2) 之后,只需要测试奇数 个因素。
对于 32 位(无符号)类型,质因数将少于 (32) 个。这为用于存储连续素数因子的固定大小数组提供了一个简单的上限。根据使用的算法,数组中的质因子按升序排列。
(24) => {2,2,3}
,
您可以使用适当的标点符号输出因子:
// Output the prime factors of a number
void factorize(int num) {
int n = num; // save the initial value of num
const char *sep = ""; // initial separator is an empty string
for (int i = 2; i <= num / i; i++) { // stop when num is reduced to a prime
while (num % i == 0) { // while the input is divisible to "i"
num = num / i; // divide the num by "i" (remove the factor)
printf("%s%d",sep,i); // print the separator and the factor.
sep = " x "; // change the separator for any further factors
}
}
if (num > 1 || n <= 1) {
printf("%s%d",num); // print the last or single factor.
}
printf(" = %d\n",n); // print the rest of the equation
}