2014-12-03 31 views
-4

我創建了一個程序,可以將給定的偶數分解爲兩個素數之和。C++將偶數分解爲質數

#include <iostream> 
#include <stdio.h> 
using namespace std; 

int i(int x, int y) 
{ 
    if (x > y) 
    { 
     if (x % y) 
      return i(x, y + 1); 
     else 
      return 0; 
    } 
    else 
     return (x > 1); 
} 

int main() 
{ 
    int a, b; 

    do 
    { 
     cout << "Please input a positive even number: "; 
     cin >> a; 

     if (a % 2 == 0 && a >= 1) 
     { 
      for (b = a/2; b > 1; b--) 
      { 
       if ((i(b, 2) && i(a-b, 2)) && 
        printf("%i + %i\n", b, a-b)); 
      } 
     } 
     else if (a % 2 != 0 && a >= 1) 
     { 
      cout << a << "="<< a << endl; 
     } 
     else 
      break; 
    } 
    while(a >= 4); 

    return 0; 
} 

不過,我想打破偶數爲一個素因子相乘首要因素,例如,12 = 2 * 2 * 3。修改程序的任何提示?感謝您的幫助

+2

https://www.google.com/search?q=prime+factorization+c%2B%2B – IdeaHat 2014-12-03 14:18:15

+2

您所提供的代碼中有共同的幾乎沒有與你的目標。你所要求的是所謂的分解,並且是無止境的重新審視。四處挖掘,並提出更具體的問題。 – MariusSiuram 2014-12-03 14:23:01

回答

1

檢查了這一點:

// A function to print all prime factors of a given number n 
void primeFactors(int n) 
{ 
    // Print the number of 2s that divide n 
    while (n%2 == 0){ 
     printf("%d ", 2); 
     n = n/2; 
    } 

    // n must be odd at this point. So we can skip one element (Note i = i +2) 
    for (int i = 3; i <= sqrt(n); i = i+2){ 
     // While i divides n, print i and divide n 
     while (n%i == 0){ 
      printf("%d ", i); 
      n = n/i; 
     } 
    } 

    // This condition is to handle the case when n is a prime number 
    // greater than 2 
    if (n > 2){ 
     printf ("%d ", n); 
    } 
} 

http://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/

+0

哦,謝謝。此代碼似乎與我的預期更相關 – Amy 2014-12-03 14:28:01

+0

很高興爲您提供幫助! :D – 2014-12-03 14:31:59

0

它可能不是最好的解決你的問題,但你可以去爲它或有限目的:-)

int r,q,a,i; 
    cout << "Please input a positive even number: "; 
    cin >> a; 

    if (a % 2 == 0 && a >= 1) 
    { 
    for (i=2;i<=a;i++) 
    { 
     r=a%i; 
     while (r==0) 
     { 
      cout<<i<<"*"; 
      q=q/i; 
      r=q%i;  
     } 
    } 
    else 
    { 
    cout<<"Number is not even"; 
    } 
+0

感謝您的幫助。這個計劃真的很鼓舞人心。 – Amy 2014-12-03 14:52:22

+0

不客氣:-)你可以通過將它標記爲給定刻度標記上的答案來支持我:-P – 3Demon 2014-12-03 14:59:12