c - 十进制素数转二进制

标签 c binary decimal

我尝试将十进制素数转换为二进制格式...我有 2 个不同的工作代码块,但我不知道如何与它们集成。

这是我的质数代码:

#include <stdio.h>
#include <math.h>

int main(){
    int num, sr, num2;
    int isPrime = 1; 
    printf("Prime\t    | Binary\n");
    printf("============================\n");
    for(num=2; num<=100; num++){
        sr = (int) sqrt(num);
        for(num2=2; num2 <= sr; num2++){
            //num2 <== sr to stop the innner loop
            if(num%num2 == 0){
                isPrime = 0;
                break;
            }
        }
        if(isPrime){
            printf("%d\t    |\n", num);
            isPrime = 1;
        }else{
            isPrime = 1; 
        }
    }
    return 0;
}

这是十进制转二进制:

int decimalNumber,remainder,quotient;
int binaryNumber[100],i=1,j;
while(quotient!=0){
     binaryNumber[i++]= quotient % 2;
     quotient = quotient / 2;
}

for(j = i -1 ;j> 0;j--)
     printf("%d",binaryNumber[j]);

我想要的:

Prime       | Binary
=====================
2           | 10
3           | 11
...

最佳答案

基本上,您只需将代码复制并粘贴到正确的位置(稍作更改或 2)。

...
if(isPrime){
   int quotient = num;
   int binaryNumber[100],i=1,j;

   printf("%d\t    |", num);

   while(quotient!=0){
      binaryNumber[i++]= quotient % 2;
      quotient = quotient / 2;
   }

   for(j = i -1 ;j> 0;j--)
      printf("%d",binaryNumber[j]);

   printf("\n");
   isPrime = 1;
}
...

Test.

But a function is probably better. It would look something like:

void printBinary(int decimalNumber)
{
    int quotient = decimalNumber;
    int binaryNumber[100],i=1,j;
    while(quotient!=0){
        binaryNumber[i++]= quotient % 2;
        quotient = quotient / 2;
    }

    for(j = i -1 ;j> 0;j--)
        printf("%d",binaryNumber[j]);
}

你会调用它

printBinary(num);

Test .

关于c - 十进制素数转二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15465820/

相关文章:

c - 如何在 Sublime Text 2 中运行 C 程序

c - 嵌入式设备可能的堆栈大小

Python形态学n_ary_converter

mysql - 在mysql用户定义函数中如何设置动态返回数据类型

c++ - C++中的整数到十六进制字符串

c - 如何读取procfs文件?

c - pthread 和有点 "broadcast stream"

bash:在预定义位置拆分二进制文件

amazon-web-services - AWS API GATEWAY 配置以从 lambda 返回二进制 pdf 文件

c# - 将字符串转换为小数忽略点