UVa-10193
Zerojudge d306
內容一樣,但是讀檔版本。
解題思路:
大致上就是把從二進位轉回十進位,然後判斷最大公因數。
程式碼:
#include<stdio.h>
#include"FileHandler.h"
int gcd(int a, int b)
{
if (a == 0 || b == 0)
return a + b;
while ((a %= b) != 0 && (b %= a) != 0);
return a + b;
}
int main()
{
char *str = readAllTextFromFile("../love.txt");
int n=0,i=0;
while(str[i]!='\n')//read amount
{
n = str[i] - '0' + n * 10;//change char to int
i++;
}
i++;
for (int j = 0; j < n; j++)
{
int s1 = 0, s2 = 0,num1=0,num2=0,bi=1,x=0,check=0;
while (str[i] != '\n'&&str[i]!=NULL)//read number s1
{
if (x == 0 && str[i] == '0')//if first digit is 0, it is invalid
check = 1;
s1 = str[i] - '0' + s1 * 10;
i++;
x++;
}
i++;
x = 0;
while (str[i] != '\n'&&str[i]!=NULL)//read number s2
{
if (x == 0 && str[i] == '0')
check = 1;
s2 = str[i] - '0' + s2 * 10;
i++;
x++;
}
i++;
printf("%d %d\n", s1, s2);
while (s1 > 0)//turn binary to decimal
{
num1 += (s1 % 10)*bi;
bi *= 2;
s1 /= 10;
}
bi = 1;
while (s2 > 0)
{
num2 += (s2 % 10)*bi;
bi *= 2;
s2 /= 10;
}
printf("Pair #%d: ", j + 1);
if (s1 < 0 || s2 < 0||check==1||num1<=1||num2<=1)//if each length smaller than 2 is also invalid
{
printf("invalid input.\n");
}
else if (gcd(num1, num2) != 1)
printf("All you need is love!\n");
else
printf("Love is not you need!\n");
if (str[i] == NULL)
break;
}
system("pause");
return 0;
}
沒有留言:
張貼留言