这里我在找因子数的位置
例如
当用户进入运行时10时
1 2 5 10
当用户进入因子3的位置时
然后返回第3个因子意味着5
例如
当用户进入运行时20时
1 2 4 5 10 20
当用户进入因子5的位置时
然后返回第5因子意味着10
我创建了一个程序,但是还有一件事就是找到因子数的位置
#include<iostream>
using namespace std;
int Factor(int n) {
int i,j=0;
for(i=1;i<=n;i++)
{
if(n%i==0) //10mod1=0 reminder
{
//j=i; //here i am storing the factor number
cout << i ;
}
}
return i;
}
int main()
{
int x;
cout << "Enter your factor number:";
cin >> x;
Factor(x);
return 0;
}
直播节目链接:https://onlinegdb.com/hj4yayxzw
现在我要做的是找到因子数的位置
求因子数位置逻辑的实现
帮助
在for循环中,您可以维护找到的因子的计数,如果计数到达该位置,则该位置的因子就是您想要的答案。
您既可以在那里返回这个答案本身,也可以将它存储在局部变量中,并在函数末尾返回它。
解释此逻辑的代码:
#include<iostream>
using namespace std;
int Factor(int n, int factorPosition) {
int i,j=0;
int factorsSoFar = 0;
int factor = -1;
for(i=1;i<=n;i++)
{
if(n%i==0) //10mod1=0 reminder
{
factorsSoFar++; //here i am storing the factor number
if(factorsSoFar == factorPosition){
factor = i;
break;
}
}
}
return factor;
}
int main()
{
int x, position;
cout << "Enter your factor number: ";
cin >> x;
cout << "Enter the factor position: ";
cin >> position;
int factor = Factor(x,position);
if(factor == -1){
cout<<"No factor exists for position "<< position<<endl;
}else{
cout<<"Factor is: "<<factor<<endl;
}
return 0;
}
在for循环中,您可以计算因子的索引(位置)。 我使用bits/stdc++.h
,因为它比iostream
快。 我试图用简单的方式编写这个问题,并看到您的int j=0
变量未被使用。
所以这是我的方式:
#include<bits/stdc++.h>
using namespace std;
void Factor(int n , int position){
int i,count=0;
for(i=1;i<=n;i++)
{
if(n%i==0) //10mod1=0 reminder
{
count++; // count position
//here i am storing the factor number
if (count==position){
cout<<"factor of position "<<position<<" is "<<i<<"\n";
break;
}
}
}
if (position>count)
cout<<"no factor for this position\n";
}
int main()
{
int factor,position;
cout << "Enter your factor number: ";
cin >> factor;
cout << "Enter the factor position: ";
cin >> position;
Factor(factor,position);
}