In: Computer Science
CODE MUST BE IN C++ write a program that loops a number from 1 to 10 thousand and keeps updating a count variable (count variable starts at 0 ) according to these rules: n1 = 14 n2 = 54 n3 = 123 if the number is divisible by n1, increase count by 1 if the number is divisible by n2, increase count by 2 if the number is divisible by n3, increase count by 3 if none of the above conditions match for the number, increase count by the number.
The program must produce one numeric output (it should be the value of count)
Note: If the library <bits/stdc++.h> is not present on your local machine. You can alternatively use <iostream> and <stdio.h> for running the below code snippet(just uncomment them and comment out <bits/stdc++.h>)
C++ Code snippet:
#include<bits/stdc++.h>
//#include<stdio.h>
//#include<iostream>
using namespace std;
int main()
{
  
    int num = 1;                 // initializing the variables
    int count = 0;               // initializing count = 0
    int n1 = 14;
    int n2 = 54;
    int n3 = 123;
    int flag1 = 0;              // initializing the flags to check for conditions
    int flag2 = 0;
    int flag3 = 0;
    while(num <= 10000){        // looping until 10000
      flag1 = 0;                // reseting flags
      flag2 = 0;
      flag3 = 0;
      if(num%n1==0){             // if num is divisible by n1
        count += 1;
        flag1 = 1;               // set flag1 to 1
      }
      if (num%n2==0){
        count += 2;
        flag2 = 1;               // set flag2 to 1
      }
      if (num%n3==0){
        count += 3;
        flag3 = 1;               // set flag3 to 1
      }
      if (!(flag1||flag2||flag3)){ // if all flags are 0, then none of the above conditions
        count += num;              // got executed, so increment count by num
      }
      num += 1;
    }
    cout << count << " ";        // return result
  return 0;
}
Code Output :
