打印两个数字的第k个公因子
给定两个数字x和y,输出应包含它们的第k个公因子。
Input: x=9 y=18 k=1 Output : k common factor = 2 Factors of 9 : 1, 3, 9 Factors of 18 : 1, 2, 3, 6, 9, 18 Greatest Common Factor : 9
算法
START Step 1 -: take input as x and y lets say 3 and 21 and k as 1 Step 2 -: declare start variables as int i,num,count=1 Step 3 -: IF x<y Set num=x End IF Step 4 -: Else Set num=y End Else Step 5 -: Loop For i=2and i<=num and i++ IF x % i==0 and y % i == 0 Count =count +1 End If IF count=k Print i End IF Else Return -1 End Else Step 6 -: End Loop For STOP
示例
#include<stdio.h>
int main() {
int x = 3, y = 21, k = 1; // taking x and y as two number and k is limit for their common factor
int i,num,count=1;
if(x<y) //fetching smaller value in num[poi
num=x;
else
num=y;
for (i=2; i<=num; i++) { //loop from 2 till smaller value
if (x % i==0 && y % i == 0) //if remainder is 0 increment count
count++;
if (count == k)
printf("%d",i);
else
printf("no value as there are less factors than k between x and y ");
break;
}
return 0;
}输出结果
如果我们运行上面的程序,那么它将生成以下输出。
their kth common factor is : 2
热门推荐
8 哈尼族祝福语简短
10 简短的古风生日祝福语
11 春节福字祝福语简短
12 三八祝福语简短文案
13 团队虎年祝福语简短霸气
14 饭桌祝福语长辈文案简短
15 晋城春节祝福语简短英文
16 接亲祝福语女生文案简短
17 盘锦结婚祝福语大全简短
18 疫情对妈妈祝福语简短