将C中的数字分解

时间:2016-12-12 17:35:33

标签: c

我想做一个像这样的分解程序:72 = 3 * 2 ^ 3 ^ 2

用C语言编写,我该怎么办?

我试图这样做,但我不能这样做:

#include <stdio.h>

int main(){

int n;
int j;

printf("Insert a positive integer number greater than 1\n")
scanf("%d", &n);
j = 2;
do
{
  if( n % j == 0)
  {
     printf("%d\n", j);
     n = n / j;
  }

  else{
     j++;
     }
}

while ( n > 1);
}

2 个答案:

答案 0 :(得分:1)

假设给定72,你想输出2^3 X 3^2这个代码应该这样做:

/* Decides when to print multiplication sign */
const char *get_mult_string()
{
    static int first_divisor=1;

    if (first_divisor==1) {
        first_divisor=0;
        return "";
    } else {
        return " X ";
    }

}

void factorize() {
    int n;
    int j;

    printf("Insert a positive integer number greater than 1: ");
    scanf("%d", &n);
    j = 2;
    int power_count=0;

    do {
        if (n % j == 0) {
            power_count++;
            n = n / j;
        }

        else {
            if (power_count>0) {
                printf("%s(%d^%d)", get_mult_string(), j, power_count);
                power_count=0;
            }
            j++;
        }
    }

    while (n > 1);
    if (power_count>0) {
        printf("%s(%d^%d)\n", get_mult_string(), j, power_count);
    }

}

答案 1 :(得分:0)

尝试创建一个数组,其中每个槽代表一个素数,并将它们全部初始化为0.例如,array [0]表示2,array [1] 3,array [2] 5,array [3] 7 ,array [4] 11。

当您到达它时,而不是像在代码中那样打印出素数,而是增加数组中的那个插槽。最后,您可以拨打 +(bool)CheckValuesInKeyChainWithUsername:(NSString*)username { NSMutableDictionary* dictSearch = [[NSMutableDictionary alloc]init]; [dictSearch setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass]; [dictSearch setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit]; [dictSearch setObject:(__bridge id)kCFBooleanTrue forKey:(__bridge id)kSecReturnAttributes]; [dictSearch setObject:username forKey:(__bridge id)kSecAttrAccount]; /* Unique string used to identify the keychain item: //static const UInt8 kKeychainItemIdentifier[] = "com.company.MyApp"; NSData *keychainItemID = [NSData dataWithBytes:kKeychainItemIdentifier length:strlen((const char *)kKeychainItemIdentifier)]; [dictSearch setObject:keychainItemID forKey:(__bridge id)kSecAttrGeneric]; */ NSMutableDictionary* found = nil; CFMutableDictionaryRef foundCF = nil; OSStatus errOS = noErr; errOS = SecItemCopyMatching((__bridge CFDictionaryRef) dictSearch, (CFTypeRef*)&foundCF); NSLog(@"%d",(int)errOS); if (errOS == errSecItemNotFound) { return false; }else if (errOS == noErr) { found = (__bridge NSMutableDictionary*)(foundCF); return true; } return false; }

之类的内容

注意:switch语句可能是你的朋友。