Project Euler 3 - Highest Prime Factor

前端 未结 2 1041
-上瘾入骨i
-上瘾入骨i 2021-01-28 03:52

before I start I want to clarify that I am not looking for code examples to get the answer; that would defeat the object of Project Euler.

The problem

相关标签:
2条回答
  • 2021-01-28 04:10
    # Possible solution  but still its *time consuming* but answer can be guessed by the last option in console output 
    
    #include<stdio.h>
    #include<string>
    #include<iostream>
    #include<math.h> 
    int prime(unsigned long long); 
    using namespace std; 
    int main(){ 
    unsigned long long ii, ij; unsigned long long in; 
    cin>>in; ij = ceil(in/2); 
    if( (ij % 2) == 0 ) ij -= 1; 
    for(ii = 3 ;ii < ij;ii+= 2){
    if(in % ii == 0){
            if(prime(ii) == 1 ){
        cout<<" ans "<<ii<<endl;
        }
    } 
    } 
     return 0; 
    } 
     int prime(unsigned long long ii){  
    unsigned long long ij;
      for(ij = 3;ij < ii/2 ;ij += 2){ 
        if( (ii % ij) ==0){
           return 0;    
        }       
      }
      return 1; 
     }
    
    0 讨论(0)
  • 2021-01-28 04:31

    If you start div at 2 and count up instead of down, and divide it out from the number when the modulo is zero, you gain two big advantages that are useful here:

    1. You don't have to check if div is prime, since it can't be composite because any prime factors smaller than it would already have been divided out.
    2. You reduce the remaining problem size every time you find a factor, and, as it turns out, the input number has fairly small prime factors.

    You could then also break once div*div is greater than the remaining number, as you know at that point that it must be a prime. This is because any divisors greater than the square root are "paired" with one less than the square root. However, since this is an "easy" problem, this optimization is not needed here (although it is useful for later problems).

    0 讨论(0)
提交回复
热议问题