2015年8月10日 星期一

[C][瘋狂程設][04_分支] A017:三角形種類

A017:三角形種類


三角形種類

輸入為三角形三邊長(正整數) a b c,輸出三角形類型(英文)
 isosceles triangle(等腰三角形)
 not a triangle(不成三角形)
 regular triangle(正三角形)
 rectangular triangle(直角三角形)
 obtuse triangle(鈍角三角形)
 acute triangle(銳角三角形)
 isosceles righttriangle(等腰直角三角形)

Input

 1 1 5

Output

not a triangle

Notes:


1.先將三角三個邊長做排序:

2.判別不成三角形,若邊長無法構成三角形,則程式結束:

 //situation:not a triangle
 if(side1+side2<=side3){
  printf("not a triangle");
  return 0;
 } 

3.先判別正三角形或等腰三角形,若為等腰三角形,則程式結束,不需要辨別是鈍角或銳角

 //situation:regular or isosceles
 if((side1==side2) && (side2==side3)){
  printf("regular triangle");
  return 0;
 }else if((side1==side2) || (side2==side3)){
  printf("isosceles triangle");
  return 0;
 }

4.判別鈍角、銳角、直角三角形

int test_side_square(int *a,int *b,int *c){

 int value,a2=(*a)*(*a),b2=(*b)*(*b),c2=(*c)*(*c);;
 
 //value=0, means: rectangular triangle(直角三角形)
 //value=1, means: obtuse triangle(鈍角三角形) 
 //value=-1,means: acute triangle(銳角三角形)
 (c2==(a2+b2))?(value=0):(c2>(a2+b2))?(value=1):(value=-1);
 
 return value;
}

5.若為直角三角形,則需要進一步辦別是否具有等腰性質:

 //situation:obtuse or acute;rectangular or isosceles righttriangle,
 result=test_side_square(&side1,&side2,&side3); 
 if(result!=0){
  (result<0)?printf("acute triangle"):printf("obtuse triangle");
 }else{
  (side1==side2)?printf("isosceles righttriangle"):printf("rectangular triangle");
 }

Code:

#include <stdio.h>

void swap(int *a,int *b){
 if(*a>*b){
  *a^=*b;
  *b^=*a;
  *a^=*b;
 }
}

int test_side_square(int *a,int *b,int *c){

 int value,a2=(*a)*(*a),b2=(*b)*(*b),c2=(*c)*(*c);;
 
 //value=0, means: rectangular triangle(直角三角形)
 //value=1, means: obtuse triangle(鈍角三角形) 
 //value=-1,means: acute triangle(銳角三角形)
 (c2==(a2+b2))?(value=0):(c2>(a2+b2))?(value=1):(value=-1);
 
 return value;
}

int main(void){

 int side1,side2,side3,result;
  
 scanf("%d %d %d",&side1,&side2,&side3);
 //printf("%d %d %d",side1,side2,side3);

 //sort the length of side
 swap(&side1,&side2);
 swap(&side2,&side3);
 swap(&side1,&side2);

 //situation:not a triangle
 if(side1+side2<=side3){
  printf("not a triangle");
  return 0;
 } 

 //situation:regular or isosceles
 if((side1==side2) && (side2==side3)){
  printf("regular triangle");
  return 0;
 }else if((side1==side2) || (side2==side3)){
  printf("isosceles triangle");
  return 0;
 }
 
 //situation:obtuse or acute;rectangular or isosceles righttriangle,
 result=test_side_square(&side1,&side2,&side3); 
 if(result!=0){
  (result<0)?printf("acute triangle"):printf("obtuse triangle");
 }else{
  (side1==side2)?printf("isosceles righttriangle"):printf("rectangular triangle");
 }
 
 return 0;
}


[C][瘋狂程設][04_分支] A016:三數排序

A016:三數排序


三數排序

輸入三個正整數a、b、c,將a、b、c從小排到大。
鍵詞
<:鍵詞 至少=0 最多=1 擁有=9999>include<:>
<:鍵詞 至少=0 最多=0 擁有=9999>[<:>
<:鍵詞 至少=0 最多=0 擁有=9999>]<:>

Input

192 706 184 

Output

184 192 706

Notes:


1.兩數字比較大小,數字小的在前面,數字大的在後面

利用邏輯運算子,若數字小的在後面,則將兩個數字互換
void swap(int *a,int *b){
 if(*a>*b){
  *a^=*b;
  *b^=*a;
  *a^=*b;
 }
}

2. 先將數字1數字2比較,再將數字2與數字3比較,最後數字1與數字2再比一次,確保最小的數字在第一個

 swap(&num1,&num2);
 swap(&num2,&num3);
 swap(&num1,&num2);

Code:

#include <stdio.h>

void swap(int *a,int *b){
 if(*a>*b){
  *a^=*b;
  *b^=*a;
  *a^=*b;
 }
}

int main(void){

 int num1,num2,num3;

 scanf("%d %d %d",&num1,&num2,&num3);
 
 swap(&num1,&num2);
 swap(&num2,&num3);
 swap(&num1,&num2);

 printf("%d %d %d",num1,num2,num3);
 return 0;
}

[C][瘋狂程設][02_變數與型別] F007:輸入ASCII及字元顯示

F007:輸入ASCII及字元顯示


輸入一個ASCII數字,輸出數所代表之字元及ASCII碼,再輸出ASCII表上的下一個字元及其ASCII碼

Input

117

Output

u:117↵\r\n
v:118

Notes:


1.字元與ASCII的表示方式

這題花很多間在想字元與ASCII的表示方式,
input的給是數字,一開始因為這個混淆了很久。

到底型別要用char還是int? 
最後幾次測試還有google的結果:型別採用int即可!!
要顯示字元,就用"%s",要顯示ASCII,就用"%d"

當int的數字用%s顯示,就可以印出該ASCII所代表的文字,
ASCII code的數字+1,就可以印出下一個字。
printf("%s:%d\n",&input,input);

2.ASCII的相關資訊

https://zh.wikipedia.org/zh-tw/ASCII

3.重要的ASCII code

32:space
48:0
49:1
65:A
97:a

Code:

#include 

int main(void){

 int input=0,next=0;
 
 scanf("%d",&input);
 printf("%s:%d\n",&input,input);
 
 next = input+1;
 printf("%s:%d",&next,next);
 
 return 0;
 
}

[C][瘋狂程設][02_變數與型別] A014 次方求餘

A014 次方求餘


輸入三個正整數 n p d,輸出(n^p)%d,即 n 的 p次方 對 d的餘數。 

Input

 59 89 80 

Output

  
59

Notes:


1.這題看似簡單,卻包含一個數學陷阱。簡單的求餘數不難,但是這題有個小陷阱,就是"次方",取次方可能會出現極大數字,造成溢位。

因此利用迴圈處理次方的運算,每次迴圈當中,持續將每次增加的底數去餘數,之後再取一次餘數,利用這個方式避免溢位。
例如:

5%3 = 2
25%3 = 1

(5*5)%3  = (5*(5%3))%3
         = (5*2)%3  
         = 10%3=1

while(i<index){
  remider=(remider*(base%divisor))%divisor;
  i++;
 }

Code:

#include >stdio.h<

int main(void){

 int base=0,index=0,divisor=0,remider=1,i=0;
 
 scanf("%d %d %d",&base,&index,&divisor);

 while(i<index){
  remider=(remider*(base%divisor))%divisor;
  i++;
 }
 
 printf("%d",remider);

 return 0;
}

[C][瘋狂程設][01_變數與計算] M90H007:考試調分(低成60高100)

M90H007:考試調分(低成60高100)

考試調分(低成60高100)

在一次程設小考中,同學成績表現不好,老師決定採線性調整分數,
將最低分調成60分,將最高分調成100分。
所有同學的調整後的分數採四捨五入進整數。 
輸入60個同學的成績,輸出同學調整後的成績。   

Input

 44 59 68 42 37 14 65 58 29 34 56 60 54 64 9 5 22 56 21 56 3 67 70 70 59 65 39 31 24 66 16 25 67 58 44 52 8 45 22 61 32 43 69 44 61 11 65 14 38 30 41 60 39 24 6 42 4 8 6 54 

Output

84↵\r\n
93↵\r\n
99↵\r\n
83↵\r\n
80↵\r\n
67↵\r\n
97↵\r\n
93↵\r\n
76↵\r\n
79↵\r\n
92↵\r\n
94↵\r\n
90↵\r\n
96↵\r\n
64↵\r\n
61↵\r\n
71↵\r\n
92↵\r\n
71↵\r\n
92↵\r\n
60↵\r\n
98↵\r\n
100↵\r\n
100↵\r\n
93↵\r\n
97↵\r\n
81↵\r\n
77↵\r\n
73↵\r\n
98↵\r\n
68↵\r\n
73↵\r\n
98↵\r\n
93↵\r\n
84↵\r\n
89↵\r\n
63↵\r\n
85↵\r\n
71↵\r\n
95↵\r\n
77↵\r\n
84↵\r\n
99↵\r\n
84↵\r\n
95↵\r\n
65↵\r\n
97↵\r\n
67↵\r\n
81↵\r\n
76↵\r\n
83↵\r\n
94↵\r\n
81↵\r\n
73↵\r\n
62↵\r\n
83↵\r\n
61↵\r\n
63↵\r\n
62↵\r\n
90↵\r\n

Notes:


1.讀取輸入的資料score[],並且將資料同步複製一份到sort[]

for(int i=0; i<STUDENT; i++){
  scanf("%f",&score[i]);
  sort[i]=score[i];
 }

2.將分數由小到大排序

數字兩兩相比較,數字小的放前面,數字大的放後面,數字小往前放,數字大的往後放,逐步將最小的放在第一個,最大的放在最後一個。
 //sort data
 for(int i=0; i<STUDENT; i++){
  for(int j=i; j<STUDENT; j++){
   if(sort[j]<sort[i]){
    temp=sort[j];
    sort[j]=sort[i];
    sort[i]=temp;
   }
  }
 }

3.線性代數的部分,利用最簡單的二元一次方程式的概念,求出a(coffient)與b(delta),即可對應之後的分數

 Y1=aX1+b
 Y2=aX2+b

 a=(Y1-Y2)/X1-X2
 b=Y1-aX1
coffient = (MAX-MIN)/(sort[STUDENT-1]-sort[0]);
 delta = MIN - (coffient*sort[0]);

4.計算調整之後的分數

 //adjust data and print
 for(int i=0; i<STUDENT; i++){
  score[i]=round(coffient*score[i]+delta);
  printf("%g\n",score[i]);
 }

Code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define STUDENT 60
#define MIN 60
#define MAX 100

int main (void){
 float score[STUDENT],sort[STUDENT];
 float temp=0, coffient=0, delta=0;
 
 //get data
 for(int i=0; i<STUDENT; i++){
  scanf("%f",&score[i]);
  sort[i]=score[i];
 }

 //sort data
 for(int i=0; i<STUDENT; i++){
  for(int j=i; j<STUDENT; j++){
   if(sort[j]<sort[i]){
    temp=sort[j];
    sort[j]=sort[i];
    sort[i]=temp;
   }
  }
 }

 coffient = (MAX-MIN)/(sort[STUDENT-1]-sort[0]);
 delta = MIN - (coffient*sort[0]);

 //adjust data and print
 for(int i=0; i<STUDENT; i++){
  score[i]=round(coffient*score[i]+delta);
  printf("%g\n",score[i]);
 }
 
 return 0;
}

2015年7月27日 星期一

[C][瘋狂程設][CPE考題20140325] 14A3.UVA10018:Reverse and Add

Reverse and Add

The "reverse and add" method is simple: choose a number, reverse its digits and add it to the original. If the sum is not a palindrome (which means, it is not the same number from left to right and right to left), repeat this procedure. 
For example: 
195 Initial number 
591 
----- 
786 
687 
----- 
1473 
3741 
----- 
5214 
4125 
----- 
9339 Resulting palindrome 

In this particular case the palindrome 9339 appeared after the 4th addition. This method leads to palindromes in a few step for almost all of the integers. But there are interesting exceptions. 196 is the first number for which no palindrome has been found. It is not proven though, that there is no such a palindrome. 

Task : 
You must write a program that give the resulting palindrome and the number of iterations (additions) to compute the palindrome. 

You might assume that all tests data on this problem: 
- will have an answer , 
- will be computable with less than 1000 iterations (additions), 
- will yield a palindrome that is not greater than 4,294,967,295. 

Input

The first line will have a number N with the number of test cases, the next N lines will have a number P to compute its palindrome.
3
195
265
750

Output

For each of the N tests you will have to write a line with the following data : minimum number of iterations (additions) to get to the palindrome and the resulting palindrome itself separated by one space.
4 9339 
5 45254 
3 6666 

Notes:


1.反轉輸入的數字

void reverse_data(int *num,int size,char rev_data[]){

 int m=*num;
 char data[size];
 
 /*------reverse------*/
 sprintf(data,"%d",m);
 strcpy(rev_data,data);
 strrev(rev_data);
 //printf("[%d]%d,%s,%s\n",__LINE__,size,data,rev_data);
}

Code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void reverse_data(int *num,int size,char rev_data[]){

 int m=*num;
 char data[size];
 
 /*------reverse------*/
 sprintf(data,"%d",m);
 strcpy(rev_data,data);
 strrev(rev_data);
 //printf("[%d]%d,%s,%s\n",__LINE__,size,data,rev_data);
}

int rev_and_add(int *num){

 int m=*num;
 int palindrome;
 int length=sizeof(m);
 char rev_num[length];
 
 /*------reverse------*/
 reverse_data(&m,length,rev_num);
 
 /*------add------*/
 m+=atoi(rev_num);
 length=sizeof(m);
 reverse_data(&m,length,rev_num);
 
 /*-----test palindrome, 0 means yes, 1 means no.-----*/
 char sum[length];
 sprintf(sum,"%d",m);
 //printf("[%d]%s,%s\n",__LINE__,sum,rev_num);
 
 (strcmp(sum,rev_num)==0)?palindrome=0:palindrome=1;
 //printf("[%d],p=%d\n",__LINE__,palindrome);
 *num=m;
 return palindrome;
 
 //return 0;
}

int main(void){

 int total,count,i=0,input,act;
 
 scanf("%d",&total);
 
 while(i<total){
  count=0;
  i++;
  scanf("%d",&input);
  
  do{
   //printf("[%d]count=%d\n",__LINE__,count);
   act=rev_and_add(&input);
   count++;
  }while(act==1);
   
  printf("%d %d\n",count,input);
 }

 return 0;
}

[C][瘋狂程設][CPE考題20140527] 14C2.UVA10190 : Divide, But Not Quite Conquer! :

Problem C: Divide, But Not Quite Conquer!

Your goal in this problem is to divide a certain integer n by another integer m until n = 1, obtaining a sequence of numbers. Lets call a[i] each number of this sequence, and let's say it has k numbers (i.e. you must do k-1 succesive divisions to reach n = 1). You can only have this sequence if the following restrictions are met:
a[1] = n, a[i] = a[i-1] div m, for all 1 < i <= k 
a[i] is divisible by m (that is, a[i] mod m = 0) for all 1 <= i < k 
a[1] > a[2] > a[3] ... > a[k] 
For instance, if n = 125 and m = 5, you have 125, 25, 5 and 1 (you did 3 divisions: 125/5, 25/5 and 5/5). So, k = 4, a[1] = 125, a[2] = 25, a[3] = 5 and a[4] = 1. If n = 30 and m = 3, you have 30, 10, 3 and 1. But a[2] = 10, and 10 mod 3 = 1, so there is no sequence because it violates restriction 2. When the sequence doesn't exist we think it's not fun and, thus, very boring!

input

The input will consist on an arbitrary number of lines. Each line will consist of two non-negative integers n,m which are both less than 2000000000. You must read until you reach the end of file.
125 5
30 3
80 2
81 3

output

For each pair n,m you must print the correpondent sequence a (as defined above) in a single line, with each adjacent numbers of the sequence separated by a single space. In the case the sequence doesn't exist because it violates some restriction, just print the phrase "Boring!" in a single line (without the quotes).
125 25 5 1
Boring!
Boring!
81 27 9 3 1

notes:


1.利用題目給定輸入的最大值"2000000000",設定array的大小

The input will consist on an arbitrary number of lines. 
Each line will consist of two non-negative integers n,m which are both less than 2000000000.

#define MAX 2000000000>>20


2.計算divide的答案。必須要排除除數為0的狀態,所以加上一個bool值"pass",協助判斷是否具有商數array

 while(scanf("%ld %ld",÷nd,&divisor)!=EOF){
   
  int number[MAX],i=1,pass=0;
  number[i]=dividend;
  
  //calculate the array
  while(number[i]>1&&divisor>1){
   i++;
   pass=1;
   number[i]=number[i-1]/divisor;
   if((number[i-1]%divisor)!=0){
    pass=0;
    break;
   }
  }
                .
                .
                . 
        }
  

Code:

#include <stdio.h>

#define MAX 2000000000>>20

int main(void){

 long int dividend,divisor;
 
 while(scanf("%ld %ld",÷nd,&divisor)!=EOF){
   
  int number[MAX],i=1,pass=0;
  number[i]=dividend;
  
  //calculate the array
  while(number[i]>1&&divisor>1){
   i++;
   pass=1;
   number[i]=number[i-1]/divisor;
   if((number[i-1]%divisor)!=0){
    pass=0;
    break;
   }
  }
  
  //show the result
  if(pass==1)
   for(int j=1;j≤i;j++)
    (number[j]==1)?printf("%d\n",number[j]):printf("%d ",number[j]);
  else
   printf("Boring!\n");
  
 }
 return 0;
}

[C][瘋狂程設][CPE考題20140923] 14E3.UVA12602:Nice Licence Plates

Nice Licence Plates

Alberta licence plates currently have a format of ABC-0123 (three letters followed by four digits).
We say that the licence plate is "nice" if the absolute difference between the value of the first part and the value of the second part is at most 100.
The value of the first part is calculated as the value of base-26 number (where digits are in [A..Z]). For instance, if the first part is "ABC", its value is 28 (0*26^2 + 1*26^1 + 2*26^0). So, the plate "ABC-0123" is nice, because |28-123|<=100.
Given the list of licence plate numbers, your program should determine if the plate is nice or not.

input

First line of the input contains an integer N (1<=N<=100), the number of licence plate numbers. Then follow N lines, each containing a licence plate in the format LLL-DDDD.
2
ABC-0123
AAA-9999

output

For each licence plate print on a line "nice" or "not nice" (without quotes) depending on the plate number being nice as described in the probem statement.
nice
not nice

Notes:


1.利用sscanf()分離出前三個字母與後四個數字

  scanf("%s",input);
  sscanf(input,"%[^-]-%d",letter,&digits);

2.計算前三個字母轉化成26進位當中所表示的數字大小

letter[0]-'A')*BASE*BASE+(letter[1]-'A')*BASE+(letter[2]-'A'

3.計算整數的絕對值: abs()

abs((letter[0]-'A')*BASE*BASE+(letter[1]-'A')*BASE+(letter[2]-'A')-digits);

Code:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

#define BASE 26 
#define MAX 100


int main(void){

 int num,i=0,digits,result;;
 char *input,letter[3];

 scanf("%d",&num);
 
 while(i<num){
  scanf("%s",input);
  sscanf(input,"%[^-]-%d",letter,&digits);
  result = abs((letter[0]-'A')*BASE*BASE+(letter[1]-'A')*BASE+(letter[2]-'A')-digits);
  printf("%s\n",abs(result)<=MAX?"nice":"not nice");
  i++;
 }
 return 0;
}

[C][瘋狂程設][03_運算子] A042_轉轉算2的冪次方、A043_十六進位檢視器

A042:轉轉算2的冪次方


輸入一個整數 n (0≤n<31),輸出2^n。
input:10
output:1024

Notes:

1.計算2的冪次方

使用 Arithmetic shift算術位移的left shift'<<'
int num=1;
num<<1: 數字1,左位移1位,表示1*2=2
num<<2: 數字1,左位移2位,表示1*2*2=4

Code:

#include <stdio.h>

int main(void){
 int input;
 scanf("%d",&input);
 printf("%d",1<<input);
 return 0;
}



A043:十六進位檢視器


輸入一段連文字,印出該連文字的十六進位資料
input: talks
output:74 61 6C 6B 73

Notes:


1.getchar

getchar會讀取每個字元,包含空白、跳格、換行字元。
scanf()只會讀取數字,並且會略過空白、跳格、換行字元。
本題若要使用scanf,擇要改寫成下列格式,才能抓到每個字元,若將%c改成%s,則只會抓到第一個字元:
        while((scanf("%c",&input)!=EOF){
  if(input!=' ')
   printf("%X ",input);
 }

2.十六進位顯示方式

使用"%x"或者"%X"皆可,差別在於結果顯示的字母是小寫或大寫,舉例如下:
    printf("%x ",input); //74 61 6c 6b 73
    printf("%X ",input); //74 61 6C 6B 73

3.去除空白字元

因為是輸入的方式,採取逐字元抓取,所以空白字元也會被抓進來處理。
但是題目的輸出不要顯示空白位元,所以要加入條件,遇到空白字元的時候不列印。
    if(input!=' ')


Code:

#include <stdio.h>

int main(void){

 int input;
 
 while((input=getchar())!=EOF){
  if(input!=' ')
   printf("%X ",input);
 }

 return 0;
}

2015年7月20日 星期一

[C][瘋狂程設][CPE考題20141223] 14G2.UVA10235:Simply Emirp


Problem G: Simply Emirp


An integer greater than 1 is called a prime number if its only positive divisors (factors) are 1 and itself. Prime numbers have been studied over the years by a lot of mathematicians. Applications of prime numbers arise in Cryptography and Coding Theory among others.
Have you tried reversing a prime ? For most primes, you get a composite (43 becomes 34). An Emirp (Prime spelt backwards) is a Prime that gives you a different Prime when its digits are reversed. For example, 17 is Emirp because 17 as well as 71 are Prime. In this problem, you have to decide whether a number N is Non-prime or Prime or Emirp. Assume that 1< N< 1000000.
Interestingly, Emirps are not new to NTU students. We have been boarding 199 and 179 buses for quite a long time!

Input


Input consists of several lines specifying values for N.

Output


For each N given in the input, output should contain one of the following:
    1. "N is not prime.", if N is not a Prime number.
    2. "N is prime.", if N is Prime and N is not Emirp.
    3. "N is emirp.", if N is Emirp.

Sample Input

17
18
19
179
199

Sample Output

17 is emirp.
18 is not prime.
19 is prime.
179 is emirp.
199 is emirp.

Notes:


1.判斷是否為質數,若為質數則回傳1,不是質數則回傳0

/*return value: 1=prime, 0=not prime*/
int is_prime(int *n){

 int num,i,result=0;
 num=*n; 
  
 // num == 2: 2 is prime.
 // num >  2: num is even, num is not prime.
 if(num%2==0){
  //printf("**[%d]\n",__LINE__);
  (num==2)?(result=1):(result=0);
  return result;
 }
 
 for(i=3;i*i<=num;i+=2){
  //printf("**[%d]\n",__LINE__);
  if(num%i==0){
   //printf("**[%d]\n",__LINE__);
   result=0;
   return result;
  }
  //printf("**[%d]\n",__LINE__);
 }
 result=1;
 return result;
}


2.整數轉字串、字串反轉、字串轉整數

#include <string.h>
int input,rev_input;
int value;
char temp[7];
char *rev_temp;

value=is_prime(&input);
sprintf(temp,"%d",input);
rev_temp=strrev(temp);
rev_input=atoi(rev_temp);

3.debug專用,顯示行號的標籤"__LINE__"

printf("**[%d]\n",__LINE__);

4.利用兩個三元運算子(條件運算子 conditional operator),化簡三選一的if else

三選一:
  if(value==1)
   printf("%d %s\n",input,PRIME);
  else if(value==2)
   printf("%d %s\n",input,EMIRP);
  else
   printf("%d %s\n",input,NOT_PRIME);
利用兩個條件運算子化簡:
  printf("%d %s\n",input,(value>1)?(EMIRP):((value<1)?NOT_PRIME:PRIME));

Code:


#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define PRIME "is prime."
#define NOT_PRIME "is not prime."
#define EMIRP "is emirp."

/*return value: 1=prime, 0=not prime*/
int is_prime(int *n){

 int num,i,result=0;
 num=*n; 
  
 // num == 2: 2 is prime.
 // num >  2: num is even, num is not prime.
 if(num%2==0){
  (num==2)?(result=1):(result=0);
  return result;
 }
 
 for(i=3;i*i<=num;i+=2){
  if(num%i==0){
   result=0;
   return result;
  }
 }
 result=1;
 return result;
}

int main(void){

 int input,rev_input;
 int value;
 char temp[7];
 char *rev_temp;
 
 while(scanf("%d",&input)!=EOF){

  value=0;  
  value=is_prime(&input);
  sprintf(temp,"%d",input);
 
  if(value>0){
   rev_temp=strrev(temp);
   rev_input=atoi(rev_temp);
   value+=is_prime(&rev_input);
  }
 
  if(value!=0 && input==rev_input)
   value--;
  
  printf("%d %s\n",input,(value>1)?(EMIRP):((value<1)?NOT_PRIME:PRIME));



[C][瘋狂程設][CPE考題20141223] 14G3.UVA264:Count on Cantor

Count on Cantor

One of the famous proofs of modern mathematics is Georg Cantor's demonstration that the set of rational numbers is enumerable. The proof works by using an explicit enumeration of rational numbers as shown in the diagram below.
displaymath27
In the above diagram, the first term is 1/1, the second term is 1/2, the third term is 2/1, the fourth term is 3/1, the fifth term is 2/2, and so on.

Input and Output

You are to write a program that will read a list of numbers in the range from 1 to tex2html_wrap_inline29 and will print for each number the corresponding term in Cantor's enumeration as given below. No blank line should appear after the last number.
The input list contains a single number per line and will be terminated by end-of-file.

Sample input

3
14
7

Sample output

TERM 3 IS 2/1
TERM 14 IS 2/4
TERM 7 IS 1/4




Code:

#include <stdio.h>

int main(void){
 int input;
 int num,i,level,sum,value,x,y;
 
 while(scanf("%d",&input)!=EOF){
  num=input;
  i=sum=level=value=0;
  
  while(sum<num){
   i++;
   sum+=i;
   level++;
  }
  value=level+1;
  
  //printf("i=%d,level=%d,sum=%d\n",i,level,sum);
  
  if(level%2==0){
   y=1+(sum-num);
   x=value-y;
  }else{
   x=1+(sum-num);
   y=value-x;
  }
  
  printf("TERM %d IS %d/%d\n",input,x,y);
 }

 return 0;
}

[C][瘋狂程設][CPE考題20150324] 15A3.UVA579:Clock Hands

ClockHand

The medieval interest in mechanical contrivances is well illustrated by the development of the mechanical clock, the oldest of which is driven by weights and controlled by a verge, an oscillating arm engaging with a gear wheel. It dates back to 1386.
Clocks driven by springs had appeared by the mid-15th century, making it possible to con- struct more compact mechanisms and preparing the way for the portable clock.
English spring-driven pendulum clocks were first commonly kept on a small wall bracket and later on a shelf. Many bracket clocks contained a drawer to hold the winding key. The earliest bracket clocks, made for a period after 1660, were of architectural design, with pillars at the sides and a pediment on top.
In 17th- and 18th-century France, the table clock became an object of monumental design, the best examples of which are minor works of sculpture.
The longcase clocks (also called grandfather clocks) are tall pendulum clock enclosed in a wooden case that stands upon the floor and is typically from 6 to 7.5 feet (1.8 to 2.3 m) in height. Later, the name ``grandfather clock'' became popular after the popular song "My Grandfather's Clock," written in 1876 by Henry Clay Work.
One of the first atomic clocks was an ammonia-controlled clock. It was built in 1949 at the National Bureau of Standards, Washington, D.C.; in this clock the frequency did not vary by more than one part in 108
Nuclear clocks are built using two clocks. The aggregate of atoms that emit the gamma radiation of precise frequency may be called the emitter clock; the group of atoms that absorb this radiation is the absorber clock. One pair of these nuclear clocks can detect energy changes of one part in 1014 , being about 1,000 times more sensitive than the best atomic clock.
The cesium clock is the most accurate type of clock yet developed. This device makes use of transitions between the spin states of the cesium nucleus and produces a frequency which is so regular that it has been adopted for establishing the time standard.
The history of clocks is fascinating, but unrelated to this problem. In this problem, you are asked to find the angle between the minute hand and the hour hand on a regular analog clock. Assume that the second hand, if there were one, would be pointing straight up at the 12. Give all angles as the smallest positive angles. For example 9:00 is 90 degrees; not -90 or 270 degrees.

Input

The input is a list of times in the form H:M, each on their own line, with $1 \le H \le 12$ and $00 \le M \le 59$. The input is terminated with the time 0:00. Note that H may be represented with 1 or 2 digits (for 1-9 or 10-12, respectively); M is always represented with 2 digits (The input times are what you typically see on a digital clock).

Output

The output displays the smallest positive angle in degrees between the hands for each time. The answer should between 0 degrees and 180 degrees for all input times. Display each angle on a line by itself in the same order as the input. The output should be rounded to the nearest 1/1000, i.e., three places after the decimal point should be printed.

Sample Input

12:00
9:00
8:10
0:00

Sample Output

0.000
90.000
175.000

Notes:


1.說明常數定義

#define DEGREE_HOUR 30 //時針每個小時轉30度(30=360/12)
#define DEGREE_MINS 6 //分針每個小時轉6度(6=360/60)
#define DEGREE_MAX 180.000 //題目規定答案要取銳角
#define PRECISION 3 //題目規定角度要取到小數點後面3位數
#define MINUTE 60 //一個小時有60分鐘

2.輸出的數字,準確度到小數點後面三位

#define PRECISION 3
printf("%.*f\n",PRECISION,result);

3. mod 的限制

% : mod運算只能用在整數,所以,若要得到銳角,不能將直接將角度除以180取餘數。

4.scanf 的用法,抓取格式化的數字輸入:

 float hr,min,result;
 scanf("%f:%f",&hr,&min);

5.輸入的中止"0:00":

        scanf("%f:%f",&hr,&min);
 while( hr!=0 || min!=0 ){
             ....
        }


Code:

#include <stdio.h>
#include <stdlib.h>

#define DEGREE_HOUR 30
#define DEGREE_MINS 6
#define DEGREE_MAX 180.000
#define PRECISION 3
#define MINUTE 60

int main(void){
 float hr,min,result;
 
 scanf("%f:%f",&hr,&min);
 
 while( hr!=0 || min!=0 ){
  
  hr=(hr+min/MINUTE)*DEGREE_HOUR;
  min*=DEGREE_MINS;
  (hr>min)?(result=hr-min):(result=min-hr);
  if(result>DEGREE_MAX)
   result=2*DEGREE_MAX-result;
  printf("%.*f\n",PRECISION,result);
  scanf("%f:%f",&hr,&min);
 }

 return 0;
} 

[C][瘋狂程設][CPE考題20150324] 15A2.UVA10783:Odd Sum

Odd Sum

Given a range [a,b], you are to find the summation of all the odd integers in this range. For example, the summation of all the odd integers in the range [3,9] is 3 + 5 + 7 + 9 = 24.

Input

There can be at multiple test cases. The first line of input gives you the number of test cases,T (1≤ T≤ 100) Then T test cases follow. Each test case consists of 2 integers a and b (0≤ a≤ b≤ 100 )in two separate lines.

Output

For each test case you are to print one line of output - the serial number of the test case followed by the summation of the odd integers in the range [a, b].

Sample Input

2
1
5
3
5

Sample Output

Case 1: 9
Case 2: 8

Notes:


1.儲存輸入的資料

total:表示資料有幾筆,也就是有多少個test case pairs陣列:存放每一筆輸入的起點a與終點b
 int total;
 scanf("%d", &total);

 int input=2*total;
 int pairs[input];
 int i=1,start,end,k,sum;
 
 while(i<=input){
  scanf("%d",&pairs[i]);
  i++;
 }


Code:

#include <stdio.h>

int main(void){

 int total;
 scanf("%d", &total);

 int input=2*total;
 int pairs[input];
 int i=1,start,end,k,sum;
 
 while(i<=input){
  scanf("%d",&pairs[i]);
  i++;
 }
 
 for(i=1;i<=input;i+=2){
  sum=0;
  (pairs[i]%2)?start=pairs[i]:start=pairs[i]+1;
  (pairs[i+1]%2)?end=pairs[i+1]:end=pairs[i+1]-1;
  for(k=start;k<=end;k+=2)
   sum+=k;
  printf("Case %d: %d\n",(i/2+1),sum);
 }
 
 return 0;
}

2015年7月14日 星期二

[html] 分享程式碼需要的技巧

1.在內文當中嵌入程式碼


參考文章:
http://pjchender.blogspot.tw/2015/03/blogger.html
http://www.ewdna.com/2012/02/google-code-prettify.html
http://shanhua0131.blogspot.tw/2014/01/code.html

關鍵字1:
<pre class="code prettyprint">
</pre>

關鍵字2:
<script src="//google-code-prettify.googlecode.com/svn/loader/run_prettify.js"></script>

2.程式碼當中顯示<>


參考文章:
http://pjchender.blogspot.tw/2015/03/blogger.html
相關網站:
http://www.opinionatedgeek.com/DotNet/Tools/HTMLEncode/Encode.aspx

notes:
&lt; &gt;

3.數學符號的次方表示法(上標字、下標字)


參考文章:
http://www.phd.com.tw/knowledge/html/text/

notes:
上標字的標籤:<sup></sup>
下標字的標籤:<sub></sub>
例子:
100=102 (10<sup>2</sup>)
氧氣的化學式O2 (O<sub>2</sub>)
------
4. 待續....


2015年7月13日 星期一

[C][瘋狂程設][CPE考題20150625] 15C3.UVA406:Prime Cuts

Prime Cuts

A prime number is a counting number ( tex2html_wrap_inline26 ) that is evenly divisible only by 1 and itself. In this problem you are to write a program that will cut some number of prime numbers from the list of prime numbers between (and including) 1 and N. Your program will read in a number N; determine the list of prime numbers between 1 and N; and print the C*2 prime numbers from the center of the list if there are an even number of prime numbers or (C*2)-1 prime numbers from the center of the list if there are an odd number of prime numbers in the list.

Input

Each input set will be on a line by itself and will consist of 2 numbers. The first number ( tex2html_wrap_inline38 ) is the maximum number in the complete list of prime numbers between 1 and N. The second number ( tex2html_wrap_inline42 ) defines the C*2 prime numbers to be printed from the center of the list if the length of the list is even; or the (C*2)-1 numbers to be printed from the center of the list if the length of the list is odd.

Output

For each input set, you should print the number N beginning in column 1 followed by a space, then by the number C, then by a colon (:), and then by the center numbers from the list of prime numbers as defined above. If the size of the center list exceeds the limits of the list of prime numbers between 1 and N, the list of prime numbers between 1 and N (inclusive) should be printed. Each number from the center of the list should be preceded by exactly one blank. Each line of output should be followed by a blank line. Hence, your output should follow the exact format shown in the sample output.

Sample Input

21 2
18 2
18 18
100 7

Sample Output

21 2: 5 7 11↵\r\n
↵\r\n
18 2: 3 5 7 11↵\r\n
↵\r\n
18 18: 1 2 3 5 7 11 13 17↵\r\n
↵\r\n
100 7: 13 17 19 23 29 31 37 41 43 47 53 59 61 67↵\r\n
↵\r\n

注意事項:

1.讀取資料輸入直到結束
 int max,amount;

 while(scanf("%d %d",&max, &amount)!=EOF){
        ...
        }
2.找出範圍內的質數(題目定義質數包含1),並將這些質數存放在array當中
  int prime[max];
  prime[1]=1;
  prime[2]=2;
  count=2;
 
  //find the prime list
  for(int num=3;num<=max;num+=2){
   is_prime=1;
   for(int j=2;j<num;j++){
    if((num%j)==0 && (j!=num)){
     is_prime=0;
     break;
    }
   }
   if(is_prime){
    count++;
    prime[count]=num;
   }
  }
3.找出要需要列印出來的質數的位置:
  if(count%2==0){
   center = count/2;
   start = center-amount+1;
   end = center+amount;
  }else{
   center = count/2+1;
   start = center-amount+1;
   end = center+amount-1;
  
  }
4.若是要列印出來的質數數量超過範圍讀處理方式:
  if(start<=0)start=1;
  if(end>=count)end=count;
5.將題目所需要的質數列印出來:
  for(int k=start;k<=end;k++){
    printf(" %d",prime[k]);
  }

Code:


#include <stdio.h>
#include <math.h>

int main(void){

 int max,amount;

 while(scanf("%d %d",&max, &amount)!=EOF){
 
  int prime[max];
  printf("%d %d:",max,amount);
 
  for(int i=1;i<max;i++){
   prime[i]=0;
  }
  
  int is_prime,count;
  int start,center,end;
 
  prime[1]=1;
  prime[2]=2;
  count=2;
 
  //find the prime list
  for(int num=3;num<=max;num+=2){
   is_prime=1;
   for(int j=2;j<num;j++){
    if((num%j)==0 && (j!=num)){
     is_prime=0;
     break;
    }
   }
   if(is_prime){
    count++;
    prime[count]=num;
   }
  }
  //for(int  l=1;l<=count;l++) printf("%d.%d\n",l,prime[l]);

  //check the how many and the site to print out.
  if(count%2==0){
   center = count/2;
   start = center-amount+1;
   end = center+amount;
  }else{
   center = count/2+1;
   start = center-amount+1;
   end = center+amount-1;
  
  }
  
  //for the exception situations
  if(start<=0)start=1;
  if(end>=count)end=count;
  
  //show the result
  for(int k=start;k<=end;k++){
    printf(" %d",prime[k]);
  }
  //printf(",count=%d,center=%d,start=%d,end=%d",count,center,start,end);
  printf("\n\n");
 }
 
 return 0;
}

[C][瘋狂程設][CPE考題20150625] 15C2.UVA10931:Parity


Problem E - Parity

Time Limit: 1 second We define the parity of an integer n as the sum of the bits in binary representation computed modulo two. As an example, the number 21 = 101012 has three 1s in its binary representation so it has parity 3 (mod 2), or 1. In this problem you have to calculate the parity of an integer 1 ≤ I ≤ 2147483647.

Input

Each line of the input has an integer I and the end of the input is indicated by a line where I = 0 that should not be processed.

Output

For each integer I in the inputt you should print a line The parity of B is P (mod 2)., where B is the binary representation of I.

Sample Input

1 2 10 21 0

Sample Output

The parity of 1 is 1 (mod 2).
The parity of 10 is 1 (mod 2).
The parity of 1010 is 2 (mod 2).
The parity of 10101 is 3 (mod 2).

注意事項


1.讀取資料到字元0:


 int input;
 scanf("%d",&input);
 while(input!=0){....}

2.利用 link list 的結構,宣告指標,儲存2進位數字:

 char *data;
 count=0;
 *(data+count)=num%BASE;


3.數字10進位轉2進位,並且將結果儲存到data:


while(num>0){
 int i=num%BASE;
 *(data+count)=num%BASE;
 count++;
 num = num/BASE;
}

並且輸出結果:
for(int j=count-1;j>=0;j--){
 printf("%d",*(data+j));
}

4.計算parity位數:

 (i==1) ? (parity+=1) : (parity+=0);

Code:

#include <stdio.h>

#define BASE 2

int main(void){

 int input,num,parity,count;
 char *data;

 scanf("%d",&input);

 while(input!=0){
 
  count=0;
  parity=0;
  num=input;
  
  while(num>0){
   int i=num%BASE;
   *(data+count)=num%BASE;
   count++;
   (i==1) ? (parity+=1) : (parity+=0);
   num = num/BASE;
  }

  printf("The parity of ");  
  for(int j=count-1;j>=0;j--){
   printf("%d",*(data+j));
  }
  
  printf(" is %d (mod %d).\n",parity,BASE);
  scanf("%d",&input);
 }

 return 0;
}



[2015/07/20][update]利用Arithmetic shift算術位移的方式改寫]


1.取出最右邊的bit:利用位元運算子'&'

  bit = 01 & num; //get the rightest bit.

2.將原數字除以2:利用位元運算子 right shift右移'>>'

  num >>= 1; // num divided by 2

3.將原數字轉成二進位的數字

從link list的1號位置開始,逐一存放每個bit的值,若有8個bits,則存放在第1號到第8號位置。(第0號位置空下來)
實作方法:用count來計算位置,注意count的起始值、以及count++的順序擺放、列印二進位數值時for loop的起點與終點寫法。
 int input,num,bit,parity,count;
 int *binary;
 
  num=input;
  bit=parity=count=0;
  
  printf("The parity of ");
  while(num>0){
   bit = 01 & num;
   parity += bit;
   count++;
   *(binary+count)=bit;
   num >>= 1;
  }
  
  for(int i=count;i>0;i--)
   printf("%d",*(binary+i));
   
  printf(" is %d (mod 2).\n",parity);

4.讀取資料的中止條件:

讀取資料直到尾端:while(scanf("%d",&input)!=EOF){...}
若讀取到的數值為0,則使用"break;"跳出 while loop,接著來到 return 0; 程式終止。
 while(scanf("%d",&input)!=EOF){
 
  if(input==0)
   break;
               ......
 }
        return 0;

Code:

#include <stdio.h>

int main(void){
 
 int input,num,bit,parity,count;
 int *binary;
 
 while(scanf("%d",&input)!=EOF){
 
  if(input==0)
   break;
   
  num=input;
  bit=parity=count=0;
  
  printf("The parity of ");
  while(num>0){
   bit = 01 & num; //get the rightest bit.
   parity += bit; // calculate the parity.
   count++;
   *(binary+count)=bit;
   num >>= 1; // num divided by 2
  }
  
  for(int i=count;i>0;i--)
   printf("%d",*(binary+i));
   
  printf(" is %d (mod 2).\n",parity);
 }
 
 return 0;
}

[C][瘋狂程設[02_變數與型別] M90H010:2^x個位數疊加

題目:

(M90H010) 2^x個位數疊加 : 輸入一整數n,計算 21+22+23+24+...+2n之個位數。

輸入:

90

輸出:

6
#include <stdio.h>

int main(){

 int index,i=1,sum=0;

 scanf("%d",&index);

 while(i<=index){
  switch(i%4){
   case 1:
    sum+=2;
    break;
   case 2:
    sum+=4;
    break;
   case 3:
    sum+=8;
    break;
   default:
    sum+=6;
  }
  i++;
 }
 printf("%d",sum%10);
 return 0;
}

[C][瘋狂程設][01_變數與型別] F020計算BMI

題目:

輸入身高(公尺)及體重(公斤),計算BMI=體重/身高平方,
若BMI< 18.5 則輸出"too thin"
若 18.5<=BMI<24 則輸出 "standard"
若 BMI>=24 則輸出 "too fat"

輸入:

240

輸出:

10↵\r\n
too thin

注意事項:

1.求次方使用函數

  pow(int 底數,float 指數),回傳值為double
  #include <math.h>

  example:input:10^2,output:100 
  pow(10,2)=100

2.浮點數顯示
去除小數點後面的0:使用%g
printf("%g",bmi);
顯示兩位整數以及四位小數:
printf("%2.4f",bmi);


-----
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#define THIN 18.5
#define FAT 24
#define LEVEL_1 "too thin"
#define LEVEL_2 "standard"
#define LEVEL_3 "too fat"

int main(void){

 float height=0,weight=0,bmi=0;
 
 scanf("%f %f", &height,&weight);
 bmi = weight/pow(height,2);

 printf("%g\n",bmi);
 
 if(bmi<THIN){
  printf("%s",LEVEL_1);
 }else if(bmi>FAT){
  printf("%s",LEVEL_3);
 }else{
  printf("%s",LEVEL_2);
 }
 
 return 0;

}

2015年7月12日 星期日

[C] 列出1~100的質數並計算質數總和

1.原理: 100 = 10*10,所以只要驗證10以內的質數即可
2.利用常數限定數值範圍
3.計算質數總和


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h> 
#define MAX 100
#define MIN 1

int main(void){

     int root=sqrt(MAX);  //sqrt():計算平方根,亦可使用pow(MAX,0.5)

    int prime[root];  //用來存放質因數for檢驗100以內的其他質因數

    int is_prime=1; //bool變數,1表示true,0表示false

     int count,num,i,j,k,l=0,sum=0;





    //create the array of prime,找出10以內的質因數



    prime[0]=2; //先將2放入質因數陣列當中
    count=1; //計算10以內的質因數個數


    for(num=3;num<root;num+=2){ //偶數必為2的倍數,所以檢查奇數即可

         is_prime=1;


        for(i=2;i<num;i++){

           if(num%i==0){

               is_prime=0; //有1與本身之外的其他因數,所以不是質數。

               break;

          }

       }


      if(is_prime){

           prime[count]=num; //抓出作為檢查標準的質因數

           count++;

      }

 }


     //for(j=0;j<count;j++) printf("[%d~%d]:%d is prime (%d)\n",MIN,MAX,prime[j],count);



      //find the prime



     for(j=2;j<=MAX;j++){


          is_prime=1;


          for(k=0;k<count;k++){


              if( j%prime[k]==0 && j!=prime[k] ){ //為了將作為檢查標準的質因數放入

                  is_prime=0;

                  break;

               }


           }


          if(is_prime){

               l++; //計算1~100以內的質數個數

                sum+=j;

               printf("%d.[%d~%d]:%d is prime.\n",l,MIN,MAX,j);

          }

     }



      printf("[%d~%d]:the sum of prime is %d\n",MIN,MAX,sum); 


     system("pause");

     return 0;

}

2015年4月30日 星期四

[php] 列出 1~100 質數並加總


1.原理: 100 = 10*10,所以只要驗證10以內的質因數即可
2.利用常數限定數值範圍
3.計算質數總和

<?php

$number = 0;
$sum = 0;
define("MAX","100");
define("MIN", "1");

echo "This is homework for php done by Anne on April 29.<br/>";

do{
if ( $number > MIN ){
switch ($number){
case 2:
case 3:
case 5:
case 7:
echo $number." is prime <br/>";
$sum += $number;
break;
default:
if( $number % 2 !=0 ){
if ($number % 3 !=0){
if ($number % 5 !=0){
if ($number % 7 !=0){
echo $number." is prime<br/>";
$sum += $number;
}
}
}
}
break;
}
}
$number ++;
}while( $number < MAX);

echo "Sum of the primes =".$sum;
?>