Find the sum of all the prime numbers less than 1000 that are 1 more than a perfect square.
For example, 2 is a prime that is 1 more than the perfect square 1.
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
Is there a pattern to classifying n such that n 2 + 1 is prime?
For example, we know that if n > 2 is odd, then n 2 + 1 is even and not prime. This rules out n = 3 , 5 , 7 , 9 , … . Similarly, for n > 3 and n ≡ 2 , 3 ( m o d 5 ) , we get that n 2 + 1 ≡ 0 ( m o d 5 ) . This rules out n = 8 , 1 2 , 1 8 , 2 2 … .
int s=0,g=0;
double a;
for(int x=1;x<=1000;x++)
{
a=Math.sqrt(x);
double y=(int)a;
if(a==y)
{int n=x+1;
for(int l=2;l<n;l++)
{
if(n%l!=0)
s=1;
else
s=2;
}
if(s==1)
g+=n;
}
}System.out.println(g);
I think it will also work
In Python, using the sympy library:
Forgive me for not writing yet another way of deciding whether a number is prime.
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 |
|
Another Solution
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 |
|
C++ solution
#include <bits/stdc++.h>
using namespace std;
int main () {
int sm = 0;
for (int i=1; i * i + 1< 1000; i++) {
int dvs=2;
int num = i*i + 1;
int nm = num;
int k = 2;
while (num > 0 && k*k < nm) {
if (num%k == 0) {
num /= k;
dvs++;
}
k++;
}
if (dvs == 2) sm +=nm;
}
cout << sm << endl;
}
In Pascal (sorry but this is the only one I've learned :p)
Input:
Output:
IN BLUEJ,
class brilliant {
public static void main()
{
int c=2;
for (int x=2;x<1000;x++)
{
double d=Math.sqrt(x);
int e=(int)d;
if (d==e)
{
int f=0;
for (int y=2;y<x+1;y++)
{
if ((x+1)%y==0)
{
f=f+1;
}
}
if (f>0)
{
}
else
{
c=c+(x+1);
}
}
}
System.out.println(c);
} }
Answer ====> c=2271
Problem Loading...
Note Loading...
Set Loading...
Java code:
Output: