0

I am still learning C++ and having an ECPC Competition tomorrow. You are given a positive integer N. Find the minimum positive integer divisible by both 2 and N. What should I do in the for loop? (still not completed)

#include <iostream>

using namespace std;

int main()
{
    int n;
    cin>> n;
    for(int i; ???;i++)
    return 0;
}

4 Answers4

3

You don't need any loop.

There are two cases. Either N is not divisible by 2, then all integers divisible by N and 2 are of the form

x = N * 2 * y

The smallest of those x has y==1.

The second case is when N is divisible by 2, then all integers divisible by N and 2 are of the form

x = N * y

The smallest of those x has y==1.

TL;DR: Do the maths first!

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
1

The result is N if N is divisible by 2, otherwise it's N*2.

int result = (N%2 == 0) ? N : N*2;
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108
Dorin Baba
  • 1,578
  • 1
  • 11
  • 23
  • Oh, I see someone already answered the question... I'll keep this answer to illustrate the use of ternary operators in this case. But are you sure this is problem's statement? It seems too easy for a CS competition – Dorin Baba Aug 19 '21 at 09:06
  • 1
    "too ease for a CS competition" its a trap. As with most of such competiion tasks you can either first solve the problem then write the code or first write complicated code and then wonder why it hits the time limit ;) – 463035818_is_not_an_ai Aug 19 '21 at 09:24
  • Are we sure that this is the optimal solution? I've encountered this on codegoda 2022 trial question, but it failed on test case number 5. This is exactly my answer and now wondering what's wrong :D – valhalla ross ferrer Jul 26 '22 at 13:54
0
#include<stdio.h>
#include<math.h>
#include<stdlib.h>
int main()
{
int i,N;
scanf("%d",&N);
for(i=1;i<100;i++)
  {
    if(i%2==0&&i%N==0)
      {
         if(i<12)
           {
             printf("%d",i);
           }
      }
  }
return 0;
}
-1

you should try using

int i=0;
while(true)
{
    i++;
    if((i%2==0) && (i%n==0))
    {
        cout<<i;
        break;
    }
}
Quest
  • 2,764
  • 1
  • 22
  • 44
  • (I didn't downvote this answer) It's an O(N), Where N is n*2. It's a very simple problem, don't brute force. You can solve it in O(1) just with a very little analysis :) – Dorin Baba Aug 19 '21 at 09:10