2015上机

2019-02-27  本文已影响0人  Chris_PaulCP3

2015

1、求出int范围内2的幂的数(✔)

#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int log_res(int value)
{
    int res = 0;
    while(value > 1)
    {
        value = value>>1;//右移一位相当于除以2 
        res++;
    }
    return res;
}
int main(int argc, char *argv[]) {
    int i;
    for(i = 1;i< 65535;i++)
    {
        if((i & (i-1)) == 0)//2的幂满足此条件
            printf("%d是2的%d次方\n",i,log_res(i));
    }
    return 0;
}

2、求出0到65535内的水仙花数(✔)

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
    int m;
    int a,b,c,d,e;
    int res;
    for(m = 1;m<=65535;m++)
    {
        if(m < 10)
            printf("%d是水仙花数\n",m);
        else if(m < 100)
        {
            a = m%10;
            b = m/10;
            res = pow(a,2) + pow(b,2);
        } 
        else if(m < 1000)
        {
            c = m/100;
            b = m/10 - c*10;
            a = m%10;
            res = pow(a,3) + pow(b,3) + pow(c,3);
        } 
        else if(m < 10000)
        {
            d = m/1000;
            c = m/100 - d*10;
            b = m/10 - d*100 - c*10;
            a = m%10;
            res = pow(a,4) + pow(b,4) + pow(c,4) + pow(d,4);
        } 
        else
        {
            e = m/10000;
            d = m/1000 - e*10;
            c = m/100 - e*100 - d*10;
            b = m/10 - e*1000 - d*100 -c*10;
            a = m%10;
            res = pow(a,5) + pow(b,5) + pow(c,5) + pow(d,5) + pow(e,5);
        }
        if(res == m)
            printf("%d是水仙花数\n",m);
    } 
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读