Click here to Skip to main content
15,895,746 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
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.


C++
#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
Posted
Updated 27-Aug-15 0:27am
v2
Comments
the_beginner 27-Aug-15 6:11am    
Also any comment or suggestion on coding will also be very appreciated, I am trying to learn C++

1 solution

Your logic looks correct to me.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900