Wow, that looks crazy.
I'm afraid i'm a beginner, so I haven't come across a problem like this before.
Can you explain this bit:
const int ul = std::ceil( std::sqrt(k) ) + 1.1 ; //
My understanding is that ul is an integer whose "ceiling" is the square root of k. I don't really see why you're adding 1.1 though.
By "ceiling" I mean something like ceiling(1.1)=2 or ceiling (5.6)=6. It's like an opposite of an integer part.
For example, if k was 169, then the ceiling(sqrt(169))= 13. Then you add 1.1 to get 14.1. The integer loop then kicks in checking numbers from 3 to 14.1.
How is this different to what I had written? I checked my checkprime function when I wrote it, and was able to find all the primes up to 500. I cross checked these with an internet base, so what went wrong here?
EDIT: Thanks for reminding me of the "sqrt" term, and also that the function should have been a boolean. I should have noticed those!
EDIT: I've messed around with it a bit and why have you put in std:ceil instead of just ceil? It still works if you get rid of the std. Is it standard practice to use std?
Also, why does ul have to be a const int? It works without a const in there.
I should probably post the amended program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
|
/*
Outputs the prime factorisation of a number.
*/
#include <iostream>
#include <cmath>
using namespace std;
bool prime(long long int k);
long long int smallestprimedivisor(long long int d);
int main(){
long long int n;
for( ; ; ){
cout << "Which number would you like to decompose into primes?:";
cin >> n;
while(!prime(n)){ cout << smallestprimedivisor(n) << 'x';
n = n/smallestprimedivisor(n); }
if(!(n==1)){cout << n;}
cout << '\n';
}
return 0;
}
bool prime( long long int k ) {
if( k < 2 ) return 0;
if( k == 2 ) return 1;
if( !(k%2) ) return 0;
int ub = ceil( sqrt(k) ) ;
for( int i = 3 ; i <= ub ; i += 2 ) if( !(k%i) ) return 0 ;
return 1 ;
}
long long int smallestprimedivisor(long long int d){
//Finds the smallest prime that divides a number
int h;
if(prime(d)){ return d;}
if(!(d%2)){ return 2; }
for(int i=3; i<=d; i+=2){ if(prime(i)){ h = d%i;
if(!h) {return i;}}}
}
|