我是对的吗? [英] Am I right in this logic?
问题描述
我遇到了一个问题:
给定一个数字X,找到可以从1到X的所有数字整除的最小数字。
我实现的逻辑是:
1)创建一个具有相同值的X元素数组。 a [0] = 1,a [1] = 2 ...等。
2)从[1]到[X-1]的第一个循环(int 0< = i< x )>
3)为每次迭代选择一个数组元素a [i](a [1]然后a [2]然后a [3] ...)
4)这个循环中的第二个循环来自a(i + 1< = j< X)
5)将此循环中的每个元素元素(a [j])除以选中的元素首先循环a [i]如果[j]%a [i] == 0和a [i]!= 1
我正在获得正确答案我检查过高达15号。
我在网上发现的这种逻辑完全不同。我也在添加代码以便更清楚(我的逻辑解释很混乱,我认为:P)。如果任何人有更好的逻辑,请建议。
I had a problem:
Given a number X, find the smallest number that will be divisible by all numbers from 1 till X.
The logic I implemented is :
1) Create a array of X elements with same value. a[0]=1,a[1]=2 ...etc.
2) First loop from a[1] to a[X-1] (int 0<=i<x)>
3) Select an element of array for each iteration a[i](a[1] then a[2] then a[3]...)
4) Second loop inside this loop from a (i+1<= j < X)
5) Divide each element of array(a[j]) in this loop with element selected in first loop a[i] if a[j]%a[i]==0 and a[i]!=1
I am getting answers right I checked upto num 15.
Its just that logic I found on net was quite different. I am also adding code so that it will be more clear (my logic explanation is quite confusing i think :P). If any one have a better logic please suggest.
#include <iostream>
#include <string>
#include <cassert>
using namespace std;
int smallest_div(int num)
{
int *array = new int[num];
int result(1);
for (int i(0);i<num;i++)>
array[i]=i+1;
for(int i=1;i<num;i++)>
{
for(int j=i+1;j<num;j++)>
{
if(array[j]%array[i]==0 && array[j]!=1 && array[i]!=1)
{
array[j]=array[j]/array[i];
}
}
}
cout <<"\nFinal Array:"<<endl;
for (int i(0);i<num;i++)>
{
result*=array[i];
cout << " "<<array[i];
}
delete[] array;
array=0;
return result;
}
int main(void)
{
int n,r;
cout << "Enter the num. :";
cin >> n;
r=smallest_div(n);
cout <<"\nSmallest divisible num = "<<r;
}
*忽略>每个for循环后签名
*Ignore > sign after every for loop
推荐答案
你的逻辑对我来说是正确的。
Your logic looks correct to me.
这篇关于我是对的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!