如何删除整数的最高有效位

如何删除整数的最高有效位

本文介绍了如何删除整数的最高有效位(例如,从547到47到7)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须编写一个程序,检查int是否是质数.如果是这样,我必须剪切最高有效位数并检查新数字是否为质数,再次剪切最高有效位数并再次检查,直到我的数字为1位数长为止.

I have to write a program where I check if an int is a prime number. If it is, I have to cut the most significant digit and check if the new number is prime, again I cut the most significant digit and check again, until my number is 1 digit long.

例如,如果我有547,我检查它是否是素数.确认为是后,我将5剪掉并检查47是否为素数,然后检查7是否为素数.

For example if I have 547, I check if it is prime. After I've verified that it is, I cut the 5 and check if 47 is prime, then I check if 7 is prime.

我需要的代码的唯一部分是减少数目的代码.很抱歉,如果我不能包含我的代码,但是目前我还不知道该怎么做.您能以算术方式还是通过函数建议解决方案? (如果存在可以执行此操作的功能)

The only part of the code I need is the one to cut the number.I'm sorry if I cannot include my code, but at the moment I have no idea how to do it. Could you suggest a solution both in an arithmetic way and by using a function? (if a function that can do that exists)

通过算术运算,我的意思是,仅通过使用标准数学运算,就可以知道例如如何削减最小有效数字:

By arithmetic I mean, just by using standard mathematical operations, I know for example how to cut the least significant digit:

num = num / 10;

所以547会变成54,依此类推.

So that 547 would become just 54 and so on.

推荐答案

有效小数位数可以由log10()确定.然后可以将其用于生成通过模算术去除MSD所需的10的整数次幂:

The number of significant decimal digits can be determined by log10(). That can then be used to generate the integer power of 10 value necessary to remove the MSD by modulo arithmetic:

#include <math.h>
#include <stdint.h>

uint32_t remove_msd( uint32_t i )
{
    return i % (int)pow( 10, floor( log10(i) ) ) ;
}

但是请注意,由于IEEE 754 64位双精度浮点的限制,该解决方案仅适用于小于2 的正整数值.在这里,我已强制uint32_t数据类型保持在此限制内(甚至更具限制性).如果要使用64位整数,则可以在有效范围内同样使用断言.

Note however that due to the limitations of IEEE 754 64-bit double precision floating-point, the solution will only work for positive integer values less than 2. Here I have enforced uint32_t data type to remain within this restriction (even more restrictive). You could equally use an assert for the valid range if you were to use 64 bit integers.

以下是int的更通用解决方案,但可以说不再是"仅通过使用标准数学运算"即可:

The following is a more general solution for int but is arguably no longer "just by using standard mathematical operations" as requested:

#include <stdlib.h>

int remove_msd( int i )
{
    int a = abs( i ) ;
    int m = 1 ;
    while( a > 10 )
    {
        a /= 10 ;
        m *= 10 ;
    }

    return i % m ;
}

这篇关于如何删除整数的最高有效位(例如,从547到47到7)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 22:34