Created
May 2, 2012 10:04
-
-
Save lithtle/2575670 to your computer and use it in GitHub Desktop.
a-b÷c に「d!」と答えた時、文系「小学校からやりなおせ」 理系「階乗とかないわー」となる自然数(a,b,c,d)の組をすべて求めよ from https://twitter.com/#!/eityans/status/196923152423591936
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ignore files | |
a.out* |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#define MAX 1000 /* 判定する最大の範囲 */ | |
/* | |
* 階乗の値であるかどうかを判定 | |
* Args: | |
* n: なんらかの整数 | |
* Returns: | |
* fact_coutner: 階乗の値 x! なら x | |
* 0: 階乗の値ではない | |
* Notes: | |
* 先に値を配列に格納してもいいのかもしれない -> allocとか | |
*/ | |
int | |
is_fact(int n) | |
{ | |
int m = 1; | |
int multiply = 1; | |
int fact_coutner = 0; | |
while(m <= n) | |
{ | |
if(m == n) | |
{ | |
return fact_coutner; | |
} | |
m *= multiply++; | |
fact_coutner++; | |
} | |
return 0; | |
} | |
/* | |
* 割り切れる数かどうかの判定 | |
* Args: | |
* b: 割られる数 | |
* c: 割る数 | |
* Returns: | |
* 1: b は c で割り切れる(解が整数) | |
* 0: b は c で割り切れない | |
* Note: | |
* 割った時に小数点以下が存在するかどうかの判定がいまいち | |
*/ | |
int | |
is_dividable(int b, int c) | |
{ | |
int i = c; | |
if(b < c) | |
{ | |
return 0; | |
} | |
while(1) | |
{ | |
if(i == b) | |
{ | |
return 1; | |
} | |
else if(b < i) | |
{ | |
return 0; | |
} | |
i += c; | |
} | |
} | |
/* | |
* a - b / c = d!となるような値であるかどうかを判定 | |
* Args: | |
* a, b, c: 整数 | |
* | |
*/ | |
int | |
match(int a, int b, int c) | |
{ | |
int result; | |
int ret; | |
if(!is_dividable(b, c)) | |
{ | |
return 0; | |
} | |
result = a - (int)((double)b / (double)c); | |
if(result < 0) | |
{ | |
return 0; | |
} | |
if((ret = is_fact(result))) | |
{ | |
return ret; | |
} | |
return 0; | |
} | |
int | |
main(void) | |
{ | |
int i, j, k, l; | |
for(i = 0; i <= MAX; i++) | |
{ | |
for(j = 0; j <= MAX; j++) | |
{ | |
for(k = 2; k <= MAX; k++) | |
{ | |
if((l = match(i, j, k))) | |
{ | |
printf("%d - %d / %d = %d!\n", i, j, k, l); | |
} | |
} | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment