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;
}
*Ignore > sign after every for loop