首页  >  文章  >  后端开发  >  暴风雨数字

暴风雨数字

PHPz
PHPz转载
2023-08-26 09:41:171177浏览

暴风雨数字

For N to be a stormer number, the highest prime factor of the expression N^2+1 must be greater than or equal to 2*N and it should be a positive integer.

For example, 4 is a stormer number. Since 4*4+1=17 has the greatest prime factor 17 itself which is greater than 8 i.e. 2*4.

但是3不是一个强力数字,因为3*3+1=10。10的最大质因数是5,小于6即2*3。

在这个问题中,我们给定一个正整数N,我们的目标是打印出前N个stormer。

输入: 4

OUTPUT: 1 2 4 5

这里是前4个斯托默数。3不是斯托默数,所以没有包括在内。

算法

  • 找到数字(N^2+1)的最大质因数,并将其存储在任意变量中。

  • Check if the prime factor is larger than or equal to 2*N.

  • If it satisfies the condition hence it is a stormer number.

  • Print all the stormer numbers until i is less than or equal to N.

方法

To implement the above algorithm in our code, we need to make two functions. First, to find out the highest prime factor for each case and second to check if it is greater than or equal to 2*N and keep printing the number if it is a stormer number simultaneously.

For finding out the highest prime factor of expression (n^2+1) for every number n −

  • We will divide the number by 2 until it gives remainder 0 and store 2 in primemax.

  • 现在,n在这一点上必须是奇数,所以我们将在一个for循环中迭代,只迭代从i=3到n的平方根的奇数。

  • Now store i in primemax and divide n by i while i divides n. When i fails to divide n then raise it by 2 and carry on.

  • 如果n是一个大于2的质数,那么在前两个步骤中n不会变成1,因此我们将n存储在primemax中并返回primemax。

The next function will be to check if the number is a stormer number or not. If it is, we will print it.

  • 我们将声明一个变量 temp 为 0,以计算前 N 个 stormer 数。

  • 从i=1开始,在temp小于N之前进行for循环迭代。

  • 检查 (i*i+1) 是否具有大于或等于 2*i 的最大质因数。如果上述条件为真,则打印 i 并将 temp 增加 1。

Example

的中文翻译为:

示例

Below is the implementation of above approach in C++ −

#include <iostream>
#include <bits/stdc++.h>

using namespace std;

int prime_factor(int n){ //for finding the maximum prime factor
   int primemax=0;
   while(n%2==0){ //if n is divided by 2 than we store 2 in primemax 
      primemax=2;
      n=n/2;
   }
   for(int i=3;i<=sqrt(n);i+=2){ // this is only for odd number 
      while(n%i==0){
         primemax=i;
         n=n/i;
      }
   }
   if(n>2){ // when n is prime number and greater than 2 
      primemax=n;
   }
   return primemax;
}
void stormer_number(int n){  //function to print first n stormer numbers
   int temp=0; // for counting the stormer number 
   for(int i=1;temp<n;i++){  // for iterating the all number 
      int check=(i*i)+1;  // for storing the (i*i)+1 value in check
      if(prime_factor(check)>=(2*i)){ //for checking the number if maximum prime is greater or equal to 2*i
         cout<<i<<" ";
         temp++;
      }
   }
}
int main(){
   int n=9;
   stormer_number(n);
   
   return 0;
}

Output

1 2 4 5 6 9 10 11 12

结论

在本文中,我们尝试解决打印前 N 个斯托默数的问题。

我们还学会了计算一个数的质因数。我希望这篇文章能帮助解决您对这个问题的所有疑惑。

以上是暴风雨数字的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除