1.一個正整數的因子是全部能夠整除它的正整數。而一個數若是剛好等於除它自己外的因子之和,這個數就稱爲完數。例如6=1+2+3(6的因子是1,2,3)。post
- #include <stdio.h>
- #include <math.h>
- int IsPerfect(int x);
- int main()
- {
- int m;
- printf("Input m:");
- scanf("%d", &m);
-
- if (IsPerfect(m))
- printf("%d is a perfect number\n", m);
- else
- printf("%d is not a perfect number\n", m);
- return 0;
- }
-
-
- int IsPerfect(int x)
- {
- int i;
- int total = 0;
-
- for (i=1;i<x;i++)
- {
- if (x%i==0)
- total = total + i;
- }
- return total==x ? 1 : 0;
- }
2.設計一個函數MaxCommonFactor()利用展轉相除法計算兩個正整數的最大公約數spa
- #include <stdio.h>
- int MaxCommonFactor(int a, int b);
- int main()
- {
- int a, b, x;
- printf("Input a,b:");
- scanf("%d,%d", &a, &b);
- x =MaxCommonFactor(a,b);
-
- if (x != -1)
- {
- printf("MaxCommonFactor = %d\n", x);
- }
- else
- {
- printf("Input error!\n");
- }
-
- return 0;
- }
-
- int MaxCommonFactor(int a, int b)
- {
- int r;
- if (a<=0 || b<=0) return -1;
-
- do{
- r=a%b;
- a = b;
- b = r;
- }while (r!=0);
-
- return a;
- }
- <pre name="code" class="cpp"><p>int <span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;"><strong>MaxCommonFactor</strong></span>(int a,int b)</p>{
- int r;
- if(a<0 || b<0) return -1;
- if(b==0)
- r=a;
- else
- r=Gcd(b,a%b);
- return r;
- }
另外一種版本:.net
- int divisor(int a,int b)
- {
- int x = a<b?a:b;
- while(x)
- {
- if(a%x==0 && b%x==0)
- break;
- --x;
- }
- return x;
- }
3.設計一個函數MinCommonMultiple(),計算兩個正整數的
最小公倍數。
- #include <stdio.h>
- int MinCommonMultiple(int a, int b);
- int main()
- {
- int a, b, x;
- printf("Input a,b:");
- scanf("%d,%d", &a, &b);
- x = MinCommonMultiple(a,b);
-
- if (x!=-1)
- printf("MinCommonMultiple = %d\n", x);
- else
- printf("Input error!\n");
-
- return 0;
- }
- int MinCommonMultiple(int a, int b)
- {
- int i;
-
- if (a<=0 || b<=0) return -1;
-
- for (i=1; i<b; i++)
- {
- if ((i*a)%b==0) return i * a;
- }
-
- return b * a;
- }
4.設計一個函數,用來判斷一個整數是否爲
素數。
- #include <math.h>
- #include <stdio.h>
- int IsPrimeNumber(int number);
- int main()
- {
- int n, ret;
- printf("Input n:");
- scanf("%d", &n);
- ret = IsPrimeNumber(n);
- if (ret!=0)
- {
- printf("%d is a prime number\n", n);
- }
- else
- {
- printf("%d is not a prime number\n", n);
- }
- return 0;
- }
- int IsPrimeNumber(int number)
- {
- int i;
-
- if (number <= 1) return 0;
- for (i=2; i<sqrt(number); i++)
- {
- if (number%i==0)
- return 0;
- }
- return 1;
- }
來自哈爾濱工業大學MOOC課件
5.迴文數
輸出全部不超過n(取n<256)的、其平方具備對稱性質的正整數(也稱爲迴文數)。設計
如: 1*1=1; 2*2=4;3*3=9;11*11=121;1,2,3,11是迴文數。code
- #include <stdio.h>
- #include <stdbool.h>
- bool isPalindrome(int num);
- bool isPalindrome(int num)
- {
- int pal = 0;
- int origin = num;
-
- while(num)
- {
- pal *= 10;
- pal += num % 10;
- num /= 10;
- }
-
- return pal == origin;
- }
- int main()
- {
- int n,i;
- scanf("%d",&n);
- for(i=1;i<n;i++)
- {
- if(isPalindrome(i*i) && i<256)
- {
- printf("%d\n",i);
- }
- }
-
- return 0;
- }