zoukankan      html  css  js  c++  java
  • UVALive2247 Prime Digital Roots

    Regionals 2001 >> South Pacific


    问题链接UVALive2247 Prime Digital Roots基础训练题,用C语言编写程序。

    问题分析

    数根是指整数的各个位的数字之和。如果其和为1位整数,则为结果;如果其和为多位整数,则再将各位数字相加,直到其和为1位数为止。

    但是,这个题有点不一样,输入的数只要是素数就可以了,如果不是素数就计算其数根,数根(可以是多位整数)是素数也就可以了。必要时,需要重复计算数根,直到只剩下1位为止。

    程序说明

    需要说明的有以下几点:

    1.输入输出需要用64位整数,所以用了long long类型;

    2.函数getroot()调用层次不会太深,所以使用递归调用;

    3.输出时,两项宽度均为7,中间有个空格。

    参考链接HDU1013 Digital Roots(解法二)


    AC的C语言程序如下:

    /* UVALive2247 Prime Digital Roots */
    
    #include <stdio.h>
    #include <math.h>
    
    /* 试除法判断一个数是否为素数 */
    int isprime(long long n)
    {
        if(n == 2 || n == 3)
            return 1;
    
        if((n & 1) == 0 || n == 1)  /* 偶数:n % 2 == 0 */
            return 0;
    
        long end = sqrt(n), i;
        for(i=3; i<=end; i+=2) {
            if(n % i == 0)
                break;
        }
    
        return i > end ? 1 : 0;
    }
    
    long getroot(long val)
    {
        int root = 0;
    
        while(val) {
            root += val % 10;
    
            val /= 10;
        }
    
        while(root >= 10 && !isprime(root))
            root = getroot(root);
    
        return root;
    }
    
    int main(void)
    {
        long long n;
        int root, okflag;
    
        while(scanf("%lld", &n) != EOF) {
            /* 判定结束条件 */
            if(n == 0)
                break;
    
            /* 计算数根 */
            if(isprime(n)) {
                root = n;
                okflag = 1;
            } else {
                root = getroot(n);
                okflag = isprime(root);
            }
    
            if(okflag)
                printf("%7lld%8d
    ", n, root);
            else
                printf("%7lld    none
    ", n);
        }
        return 0;
    }


  • 相关阅读:
    Spring学习总结之高级装配
    Spring学习总结之装配bean
    NS2安装过程中环境变量设置的问题(ns-2.35)
    =======================分割线======================================
    java的内存管理机制
    Python之面向对象编程
    Python之列表生成式
    Python之函数的参数
    Git基础级介绍
    第四次作业——个人作业——软件案例分析
  • 原文地址:https://www.cnblogs.com/tigerisland/p/7564589.html
Copyright © 2011-2022 走看看