Lowest Common Multiple Plus ——ACM

来源:互联网 发布:mac eclipse改java版本 编辑:程序博客网 时间:2024/06/18 15:54

1. Lowest Common Multiple Plus

求n个数的最小公倍数。

Input

输入包含多个测试实例,每个测试实例的开始是一个正整数n,然后是n个正整数。为每组测试数据输出它们的最小公倍数,每个测试实例的输出占一行。你可以假设最后的输出是一个32位的整数。

Sample Input

2 4 63 2 5 7

Sample Output

1270

该题只要按顺序向每两个求最小公倍数即可,并将所得倍数与下一个数字再进行运算求最小公倍数,循环最终得到所需值。
虽然原题说可以假设最后的输出是一个32位的整数,但是在中间运算过程中,可能会存在溢出问题,例如a * b可能会溢出,因此可以用a / gcd(a, b) * b来代替a * b / gcd(a, b),或者直接将定义long long a, b避免溢出。

//第一种#include <stdio.h>int gcd(int a, int b){    int x;    if(a < b){        x = a;        a = b;        b = x;    }    while(x = a % b){        a = b;        b = x;    }    return b;}int main (void){    int n, a, b;    while(scanf("%d", &n) != EOF){        scanf("%d", &a);        while(--n){            scanf("%d", &b);            a = a  / gcd(a, b) * b;//注意此处a * b可能溢出        }        printf("%d\n", a);    }    return 0;}//第二种,long long型#include <stdio.h>int gcd(long long  a, long long b){    int x;    if(a < b){        x = a;        a = b;        b = x;    }    while(x = a % b){        a = b;        b = x;    }    return b;}int main (void){    int n;    long long a, b;    while(scanf("%d", &n) != EOF){        scanf("%lld", &a);        while(--n){            scanf("%lld", &b);            a = a / gcd(a, b) * b;        }        printf("%lld\n", a);    }    return 0;}

2.汉字统计

统计给定文本文件中汉字的个数。

Input

输入文件首先包含一个整数n,表示测试实例的个数,然后是n段文本。

Output

对于每一段文本,输出其中的汉字的个数,每个测试实例的输出占一行。 Hint:从汉字机内码的特点考虑~ 

Sample Input

2WaHaHa! WaHaHa! 今年过节不说话要说只说普通话waHaHa!WaHaHa!马上就要期末考试了Are you ready?

Sample Output

149

本题主要在汉字机内码的存储特点,每个汉字站两个字节,而每个字节最高位为1,因此以十进制表示就是负数,所以只要得到为负值的个数,再除以2就是汉字的个数。(只是linux不能直接调用gets(),无法直接测试…)

#include <stdio.h>#include <string.h>int main (void){    int i, n, len, count;    char ch[1000];    scanf("%d\n", &n);    while(n--){        count = 0;        gets(ch);        len = strlen(ch);        for(i = 0; i < len; i++){            if(ch[i] < -1){                count++;            }        }        printf("%d\n", count / 2);    }    return 0;}
原创粉丝点击