I need to create a program which verifies if n is a perfect number or not.
I made this program, but for some reason when i submit it, i only get 90p / 100, saying the time limit is exceeded. Any help?
#include<iostream>
using namespace std;
long long n,i,s;
int main()
{
cin>>n;
s=0;
for(i=1;i<=n/2;i++)
{
if(n%i==0)
{
s=s+i;
}
}
if(s==n)
{
cout<<n<<" is a perfect number";
}
else
{
cout<<n<<" is not a perfect number";
}
return 0;
}
complete edit:
one thing I'd have in mind: use int, int is the "fastes type".
Sorry, I cannot be of more help :<
an other thing that comes to my mind is that you allways recalculate the value that you want to iterate to: n/2 is computed each time for(i=1;i<=n/2;i++)
you could store that value before looping
the next thing: ++i is a tiny tiny tiny tiny bit faster than i++ because no temporary variable has to be created.
Same goes for s=s+i; : s += i; is faster because no temporary variable has to be created
@Gamer2015: perfect, not prime. Has to go up to n/2.
The loop to the square root of n is adequate. One just has to remember that when n%i is 0, n % (n/i) is also. In other words, divisors occur in pairs. When you know that 2 goes into 6 3 times, that makes both 2 and 3 proper divisors of 6.
Of course, Gamer2015 didn't account for that in his code.