Day 30 算法笔记之数学问题 5.2 最大公约数与最小公倍数

1.最大公约数

欧几里得算法

#include <cstdio>
#include <cctype>
#include <cstring>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <map>
#include <sys/time.h>
using namespace std;

int gcb(int a,int b){
	if(b==0) return a;
	else return gcb(b,a%b);
}

int main(){
	
	int m,n;
	while(scanf("%d %d",&m,&n)!=EOF){
		if(m<n){
			swap(m,n);
		}
		int temp = gcb(m,n);
		printf("%d\n",temp);
	}
	
	return 0;
}

2.数组元素循环右移问题

这题不太理解的地方就在那个finish的值

这个do while循环就很细节

#include <cstdio>
#include <cctype>
#include <cstring>
#include <math.h>
#include <iostream>
#include <algorithm>
#include <map>
#include <sys/time.h>
using namespace std;

int gcb(int a,int b){
	if(b==0) return a;
	else return gcb(b,a%b);
}

int main(){
	
	int n,m;
	scanf("%d %d",&n,&m);
	
	int martix[100];
	for(int i=0;i<n;i++){
		scanf("%d",&martix[i]);
	}
	
	int start=n-m,finish=n-m+gcb(n,m)-1,next;
	
	for(int i=start;i<=finish;i++){
		int pos = i,temp = martix[i];
		
		do{
			next =(pos-m+n)%n;
			if(next!=i) martix[pos] = martix[next];
			else martix[pos] = temp;
			pos = next;
		}while(pos!=i);
	}
	
	for(int i=0;i<n;i++){
		printf("%d ",martix[i]);
	}
	printf("\n"); 
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/aixiaoxiao13/article/details/120925557