[英]Prime Factorization
因此,我的教授讓我們編寫了一個程序,該程序可以對用戶給定的數字進行最原始化。 並提供指數的答案。 因此,如果您的電話號碼是96,我將程序列出為2 x 2 x 2 x 2 x3。他希望我們將其列出為這樣。 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
塊內引入一個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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.