intmain() { int x; scanf("%d", &x); int i; int isPrime = 1; for ( i=2; i<x; i++ ) { if ( x % i == 0 ) { break; } } if ( i < x ) { printf("不是素数\n"); } else { printf("是素数\n"); } return0; }
intmain() { int x; int one, two, five; scanf("%d", &x); for ( one = 1; one < x*10; one++ ) { for ( two = 1; two < x*10/2; two++ ) { for ( five = 1; five < x*10/5; five++ ) { if( one + two*2 + five*5 == x*10 ) { printf("可以用%d个1角加%d个2角加%d个5角得到%d元\n", one, two, five, x); goto out; } } } } out: return0; }
三、应用
1.前n项求和
f(n) = 1+1/2+1/3+1/4+…+1/n
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include<stdio.h>
intmain() { int n; int i; double sum = 0.0; scanf("%d", &n); for ( i = 1; i<=n; i++ ) { sum += 1.0/i; } printf("f(%d)=%f\n", n, sum); return0; }
f(n) = 1-1/2+1/3-1/4+…+1/n
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include<stdio.h>
intmain() { int n; int i; double sum = 0.0; int sign = 1; scanf("%d", &n); for ( i = 1; i<=n; i++ ) { sum += sign*1.0/i; sign = -sign; } printf("f(%d)=%f\n", n, sum); return0; }
或者
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include<stdio.h>
intmain() { int n; int i; double sum = 0.0; double sign = 1; scanf("%d", &n); for ( i = 1; i<=n; i++ ) { sum += sign/i; sign = -sign; } printf("f(%d)=%f\n", n, sum); return0; }
intmain() { int a,b; int min; scanf("%d %d", &a, &b); if ( a<b ) { min = a; } else { min = b; } int ret = 0; int i; for ( i = 1; i < min; i++ ) { if ( a%i == 0 ) { if ( b%i == 0 ) { ret = i; } } } printf("%d和%d的最大公约数是%d.\n", a, b, ret); return0; }
等同于
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include<stdio.h> intmain() { int a,b; int t; scanf("%d %d", &a, &b); while ( b!=0 ) { t = a%b; a=b; b=t; } print("gcd=%d\n", a); return0; }
3.整数分解
反向输出
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include<stdio.h>
intmain() { int x; scanf("%d", &x); do { int d = x % 10; printf("%d", d); if ( x > 9 ) { printf(" "); } x /= 10; } while ( x > 0 ); printf("\n"); return0; }
intmain() { int x; scanf("%d", &x); int t=0; do { int d = x%10; t = t*10+d; x /= 10; } while ( x>0 ); x = t; do { int d = x % 10; printf("%d", d); if ( x > 9 ) { printf(" "); } x /= 10; } while ( x > 0 ); printf("\n"); return0; }