2104
Problem Description
Input There will be several test cases; each case input contains two integers N and M, which satisfy the relationship: 1<=M<=100000000 and 3<=N<=100000000. When N=-1 and M=-1 means the end of input case, and you should not process the data.
Output For each input case, you should only the result that Haha can find the handkerchief or not.
Sample Input
3 2
-1 -1
Sample Output
YES
最初的想法是建立一个一亿的数组(当然是不可行的),初始place=1,然后遍历n轮(n个人),place每轮累加m得到新place:如果place加上m的新place大于n,新place等于n-m。每一轮把新place记录到数组中,n轮后如果n个数字中还有数字没被遍历到,那就找不到手绢...
想法很笨..上网查了后,发现是一个求最大公约数的题,复习了辗转相除法。
核心思想就是如果n和m互质(最大公约数为1),就能找到,因为互质数的特性是最大公倍数为n*m。正好符合找到手绢的规则:没有重复的地方被遍历,这就需要每找到一个新地方的步数是m。
#include <stdio.h>
int gcd(int n, int m);
int main(){
int n,m;
int place=1;
while((scanf("%d %d",&n,&m)!=EOF)&&(n!=-1||m!=-1)){
int result=gcd(n,m);
if(result==1){
printf("YES\n");
}
else{
printf("POOR Haha\n");
}
}
return 0;
}
int gcd(int n, int m){
if (n<m){
int temp = n;
n = m;
m = temp;
}
int result = n%m;
if(result==0){
return m;
}
else{
gcd(m,result);
}
}
2028
Problem Description 求n个数的最小公倍数。
Input 输入包含多个测试实例,每个测试实例的开始是一个正整数n,然后是n个正整数。
Output 为每组测试数据输出它们的最小公倍数,每个测试实例的输出占一行。你可以假设最后的输出是一个32位的整数。
Sample Input
2 4 6
3 2 5 7
Sample Output
12
70
笔记:
1. a和b的最大公因数 × a和b的最小公倍数 = a*b
2. n个数的的最大公倍数 = 用(第一个和第二个数的最大公倍数)和第三个数求最大公倍数,再用所求的最大公倍数与第四个数求最大公倍数,知道与第n个数求最大公倍数。
#include<stdio.h>
int main()
{
int inputnum;
while(scanf("%d",&inputnum)!=EOF){
int i,num[10000];
for(i=0; i<inputnum; i++){
scanf("%d",&num[i]);
}
int lowest = num[0]/gcd(num[0],num[1])*num[1];
for(i=1; i<inputnum-1; i++){
lowest = lowest/gcd(lowest,num[i+1])*num[i+1];
}
printf("%d\n",lowest);
}
return 0;
}
int gcd(int a, int b){
if(a<b){
int temp = a;
a = b;
b = temp;
}
if(b==0){
return a;
}
int remain;
remain = a%b;
if(remain==0){
return b;
}
else{
gcd(remain,b);
}
}