gpt4 book ai didi

c - 质因数分解

转载 作者:行者123 更新时间:2023-11-30 18:39:45 25 4
gpt4 key购买 nike

所以我的教授让我们编写一个程序,对用户给出的数字进行质因分解。并以指数形式给出答案。因此,如果您的号码是 96,我会像这样列出程序 2 x 2 x 2 x 2 x 3。他希望我们像这样列出程序。 2^5 x 3^1。我该如何去做呢?

#include <stdio.h>

int main() {

int i, n;

// Get the user input.
printf("Please enter a number.\n");
scanf("%d", &n);

// Print out factorization
printf("The prime factorization of %d is ", n);

// Loop through, finding prime factors.
int cur_factor = 2;
while (cur_factor < n) {

// Found a factor.
if (n%cur_factor == 0) {
printf("%d x ", cur_factor);
n = n/cur_factor;
}

// Going to the next possible factor.
else
cur_factor++;
}

// Prints last factor.
printf("%d.\n", cur_factor);

return 0;
}

最佳答案

您可以通过在 if block 内引入 while 循环来实现此目的,计算当前素因数的幂并在此处打印出来。

#include <stdio.h>

int main()
{

int n;

// Get the user input.
printf( "Please enter a number.\n" );
scanf( "%d", &n );

// Print out factorization
printf( "The prime factorization of %d is ", n );

// Loop through, finding prime factors.
int cur_factor = 2;
while ( cur_factor < n )
{

// Found a factor.
if ( n % cur_factor == 0 )
{
int expo = 0;
while ( n % cur_factor == 0 )
{
n = n / cur_factor;
expo++;
}
printf( "%d^%d", cur_factor, expo );
if ( n != 1 )
{
printf( " x " );
}
}

// Going to the next possible factor.
cur_factor++;
}

// Prints last factor.
if ( n != 1 )
{
printf( "%d^1.\n", cur_factor );
}
return 0;
}

关于c - 质因数分解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28726078/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com