Number reduction problem

 Today I learned that one line of code can change your life. You should always always read your problem statement clearly. I have nearly lost 1.5 L increament in package because of this. 

The following code is the number reduction code. 

Q. Reduce the given number to 0 in minimum steps. and print the number of steps required. 

    conditions: 1. If found largest prime divisor, replace the number by it. 

  • divisor must not be 1 or number it self.        
                      2. If no such divisor, reduce the number by 1. 


Unfortunately , I read the 1st condition wrongly. instead of replacing it by divisor, I was dividing the number by it. 

Both codes have difference of one line of code. 

Code is as followed :


#include<iostream>

#include<math.h>

using namespace std;


class Arith{

public:

    int n;


    Arith(){

        cout<<"Enter Number"<<endl;

        cin>>n;

    }


    int maxFact(int num){

        int div=2,fact=1;

        while(num!=1){

            while(num%div==0){

                fact=div;

                num=num/div;

            }

            if(num==1){

                break;

            }

            else{

                div++;

            }

        }

        return fact;

    }


    int reduceNum(int num){

        int count=0;

        while(num!=0){

            int temp=maxFact(num);

            if(temp!=1 && temp!=num){

                //num=num/temp;        ----> to divide by largest prime divisor

                num=temp;            //-----> replace by largest prime divisor

                cout<<num<<"-->\n";

                count++;

            }

            else{

                num--;

                cout<<num<<"-->\n";

                count++;

            }

        }

        return count;

    }



};


int main(){

    Arith a;

    int steps= a.reduceNum(a.n);

    cout<<"total steps are "<<steps;

}

                         

Comments

Popular Posts