Never be fooled

来源:互联网 发布:下载淘宝到桌面 编辑:程序博客网 时间:2024/06/05 08:58

Q:  How many numbers are there in [1, 2000], which cannot be divided by neither 6 nor 8.

 /* Q: How many numbers are there in [1, 2000], which cannot be divided by 6 and 8? */
#include <stdio.h>
/* return lease common multiple */
int lcm(int x, int y);
/* return greatest common divesor */
int gcd(int p, int q);

void main(void)
{
    int a, b, ab, num;
    a = 2000/6;
    b = 2000/8;
    ab = 2000/lcm(6, 8);
    num = 2000 - (a + b -ab);

    printf("%d/n", num);
}

int gcd(int p, int q)
{
    int s, b, tmp;
    s = p<=q?p:q;
    b = p<=q?q:p;
    while (b%s != 0)
    {
         tmp = b;
         b = s;
         s = tmp%s;
    }
    return s;
}

int lcm(int x, int y)
{
    return x*y/gcd(x, y);
}

a:  canbe devided by 6

b: canbe devided by 8

ab: can be devided by both 6 and 8

|Q| = |S| - (|a| + |b| - |ab|) = 2000 - (2000/6 + 2000/8  + 2000/24)

原创粉丝点击