C++ 中数字因数的乘积
给定一个数字 n,我们需要找到它的所有因数,并找到这些因数的乘积并返回结果,即数字的因数乘积。数字的因数是可以完全整除该数字的数字,包括 1。例如,6 的因数是 - 1、2、3、6。
现在根据任务,我们需要找到数字的所有因数的乘积。
输入 - n = 18
输出 - 5832
解释 - 1 * 2 * 3 * 6 * 9 * 18 = 5832
输入 - n = 9
输出 - 27
解释 - 1 * 3 * 9 = 27
下面使用的解决问题的方法如下 -
获取输入 num。
循环从 i = 1 到 i*i<=num
检查如果 num%i==0,则检查
如果 num%i == i,则将 product 的值设置为 (product*i)%1e7
否则将 product 设置为 (product * i) % MAX 并将 product 设置为 (product * num / i) % MAX。
返回 product。
算法
Start In Function long long productfactor(int num) Step 1→ Declare and Initialize product as 1 Step 2→ For i = 1 and i * i <= num and i++ If num % i == 0 then, If num / i == i then, Set product as (product * i) % MAX Else Set product as (product * i) % MAX Set product as (product * num / i) % MAX Step 3→ Return product In Function int main() Step 1→ Declare and initialize n as 9 Step 2→ Print the result productfactor(n) Stop
示例
#include <stdio.h>
#define MAX 1000000000
// find the product of the factors
long long productfactor(int num){
long long product = 1;
for (int i = 1; i * i <= num; i++){
if (num % i == 0){
//equal factors should be multiplied only once
if (num / i == i)
product = (product * i) % MAX;
// Else multiply both
else {
product = (product * i) % MAX;
product = (product * num / i) % MAX;
}
}
}
return product;
}
int main(){
int n = 9;
printf("%lld\n", productfactor(n));
return 0;
}输出
如果运行以上代码,它将生成以下输出 -
27
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP